Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

July 28, 2011

Transform object to xml using linq

Using Linq, it’s easily possible to query various types of data like sql database, xml, objects like DataTable, ArrayList. It’s also possible to transform data into other formats like xml using linq. In this article, I will demonstrate how to query an System.Collections.ArrayList collection and then to save the data in xml format.

At first, I will create an ArrayList object and add Person objects to it. The code to do is below.

Adding objects to ArrayList
  1. ArrayList list = new ArrayList();
  2. list.Add(new Person { FirstName = "Scooby", LastName = "Doo", DateOfBirth= new DateTime(2000, 12, 31), Height=160 });
  3. list.Add(new Person { FirstName = "Bugs", LastName = "Bunny", DateOfBirth = new DateTime(1999, 2, 7), Height = 170 });
  4. list.Add(new Person { FirstName = "Peter", LastName = "Pan", DateOfBirth = new DateTime(2001, 10, 31), Height = 150 });

The Person class has 4 public properties of different data types – string, DateTime and int as shown below.

Person class
  1. using System;
  2. namespace WebApplication1.CSClass
  3. {
  4.     public class Person
  5.     {
  6.         public string FirstName { get; set; }
  7.         public string LastName { get; set; }
  8.         public DateTime DateOfBirth { get; set; }
  9.         public int Height { get; set; }
  10.  
  11.         public override string ToString()
  12.         {
  13.             return FirstName + " " + LastName;
  14.         }
  15.     }
  16. }

Person objects are added to the ArrayList list which can be queried using linq as shown in my previous post on query ArrayList using Linq. While querying the list, System.Xml.Linq.XElement objects can be created which can be saved as xml using System.Xml.Linq.XDocument’s Save() method. The code to show this is below.

Transform ArrayList to xml
  1. private void TransformToXml()
  2. {
  3.     ArrayList list = new ArrayList();
  4.     list.Add(new Person { FirstName = "Scooby", LastName = "Doo", DateOfBirth= new DateTime(2000, 12, 31), Height=160 });
  5.     list.Add(new Person { FirstName = "Bugs", LastName = "Bunny", DateOfBirth = new DateTime(1999, 2, 7), Height = 170 });
  6.     list.Add(new Person { FirstName = "Peter", LastName = "Pan", DateOfBirth = new DateTime(2001, 10, 31), Height = 150 });
  7.  
  8.     var q = from Person p in list
  9.             orderby p.FirstName
  10.             orderby p.LastName
  11.             select p;
  12.  
  13.     var query = new XElement("Persons", from Person p in list
  14.                                 select new
  15.                                 XElement("Person",
  16.                                 new XElement("FirstName", p.FirstName),
  17.                                 new XElement("LastName", p.LastName),
  18.                                 new XElement("DateOfBirth", p.DateOfBirth),
  19.                                 new XElement("Height", p.Height)
  20.                                 )
  21.                                 );
  22.  
  23.     XDocument doc = new XDocument(query);
  24.     doc.Save(Server.MapPath("transform.xml"));
  25.  
  26.     var query2 = new XElement("Persons", from Person p in list
  27.                                 select new
  28.                                 XElement("Person",
  29.                                 new XAttribute("FirstName", p.FirstName),
  30.                                 new XAttribute("LastName", p.LastName),
  31.                                 new XAttribute("DateOfBirth", p.DateOfBirth),
  32.                                 new XAttribute("Height", p.Height)
  33.                                 )
  34.                                 );
  35.  
  36.     XDocument doc2 = new XDocument(query2);
  37.     doc2.Save(Server.MapPath("transform2.xml"));
  38. }

As can be seen, the ArrayList object is queried for Person objects. This is not really needed for the code to work but is an example on how objects can be queried from ArrayList.

Using another query, “query”, XElement objects are created. The names of the XElement – that is, the names of the xml elements are arbitrary and the value of the elements are obtained from the Person object. The XElement objects are then added to XDocument object and saved as xml using XDocument.Save() method. The resultant xml looks like below.

Xml from Linq to ArrayList
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Persons>
  3.   <Person>
  4.     <FirstName>Scooby</FirstName>
  5.     <LastName>Doo</LastName>
  6.     <DateOfBirth>2000-12-31T00:00:00</DateOfBirth>
  7.     <Height>160</Height>
  8.   </Person>
  9.   <Person>
  10.     <FirstName>Bugs</FirstName>
  11.     <LastName>Bunny</LastName>
  12.     <DateOfBirth>1999-02-07T00:00:00</DateOfBirth>
  13.     <Height>170</Height>
  14.   </Person>
  15.   <Person>
  16.     <FirstName>Peter</FirstName>
  17.     <LastName>Pan</LastName>
  18.     <DateOfBirth>2001-10-31T00:00:00</DateOfBirth>
  19.     <Height>150</Height>
  20.   </Person>
  21. </Persons>

One thing to note is that the xml declaration is automatically added. DateTime field – DateOfBirth is automatically converted to its string representation.

The xml produced previously contains elements only. The Linq query could be easily updated to change the data to be the attributes of xml elements. This is shown in another query – “query2”. System.Xml.Linq.XAttribute objects are created similarly instead of XElement objects and added to XElement object which is then added to XDocument object and saved as xml. The resultant xml file looks like below.

Xml from Linq to ArrayList
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Persons>
  3.   <Person FirstName="Scooby" LastName="Doo" DateOfBirth="2000-12-31T00:00:00" Height="160" />
  4.   <Person FirstName="Bugs" LastName="Bunny" DateOfBirth="1999-02-07T00:00:00" Height="170" />
  5.   <Person FirstName="Peter" LastName="Pan" DateOfBirth="2001-10-31T00:00:00" Height="150" />
  6. </Persons>

The data looks similar to the previous xml except that they are now attributes of “Person” element instead of child elements.

June 27, 2011

Create XML using Linq to XML

Xml stands for eXtensible Markup Language that is designed to store and transfer data. An example xml file is below.

Sample Xml file
  1. <?xml version="1.0" encoding="utf-8" standalone="no"?>
  2. <!--demo on how to create xml file-->
  3. <root>
  4.   <Country id="1" name="Australia" capital="Canberra">
  5.     <state>New South Wales</state>
  6.     <state>Victoria</state>
  7.   </Country>
  8.   <Country id="2" name="India" capital="New Delhi">
  9.     <state>Maharashtra</state>
  10.     <state>Rajasthan</state>
  11.   </Country>
  12.   <Country id="2" name="Bangladesh" capital="Dhaka"><![CDATA[Bangladesh doesn't have any states.]]></Country>
  13. </root>

Xml file starts the xml declaration as in the first line. It supports comments similar to html comments as shown in line 2. It can have elements, can have attributes and can contain CData that is data that can be considered as plain text. Line 4 shows an example of element and attributes – Country is an element and id, name and capital are attributes. The value 1, Australia, etc are the values of the attributes.

In .NET, Linq to Xml makes it easy to create and parse xml documents. It’s easy to create xml, add declarations, add elements, attributes and also add data appropriately. The necessary classes are within the System.Xml.Linq namespace. Linq to Xml has XDocument class with xml documents can be created and loaded. XComment class can be used to add comments. XElement can be used to create elements and XAttribute classes can be used to add attributes to elements. XCData class can be used to add data in cdata format. An example on how to create xml using Linq to Xml is below.

Create xml using Linq
  1. private void CreateXml()
  2. {
  3.     XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "no"));
  4.  
  5.     XComment comment = new XComment("demo on how to create xml file");
  6.     doc.Add(comment);
  7.  
  8.     XElement el = new XElement("root");
  9.     XElement p1 = new XElement("Country", new object[] { new XAttribute("id", "1"), new XAttribute("name", "Australia"), new XAttribute("capital", "Canberra") });
  10.  
  11.     XElement p1city1 = new XElement("state", "New South Wales");
  12.     XElement p1city2 = new XElement("state", "Victoria");
  13.  
  14.     p1.Add(p1city1);
  15.     p1.Add(p1city2);
  16.  
  17.     XElement p2 = new XElement("Country", new object[] { new XAttribute("id", "2"), new XAttribute("name", "India"), new XAttribute("capital", "New Delhi") });
  18.  
  19.     XElement p2city1 = new XElement("state", "Maharashtra");
  20.     XElement p2city2 = new XElement("state", "Rajasthan");
  21.  
  22.     p2.Add(p2city1);
  23.     p2.Add(p2city2);
  24.  
  25.     XElement p3 = new XElement("Country", new object[] { new XAttribute("id", "3"), new XAttribute("name", "Bangladesh"), new XAttribute("capital", "Dhaka") });
  26.  
  27.     p3.Add(new XCData("Bangladesh doesn't have any states."));
  28.  
  29.     el.Add(p1);
  30.     el.Add(p2);
  31.     el.Add(p3);
  32.     doc.Add(el);
  33.  
  34.     doc.Save(Server.MapPath("country.xml"));            
  35. }

As can be seen, once the XElement, XComment, XAttribute objects are created, they got to be added to parent object. Once the necessary data has been added, the xml file can be saved using XDocument’s Save method as in line 34 above.

June 16, 2011

Query DataTable using Linq

In this example, I will show how to use Linq to query DataTable. A DataTable is a table of data stored in memory. Since Linq can query data of IEnumerable type, the data rows are declared as as IEnumerable so that Linq can query the data.

I have already setup the web application and have added a page. I will now define the schema of the DataTable and then create it. The code for creating the DataTable is below.

Create DataTable
  1. private DataTable GetDataTable()
  2. {
  3.     DataTable dt = new DataTable();
  4.  
  5.     //add columns
  6.     dt.Columns.Add("ID", typeof (Int32));
  7.     dt.Columns.Add("Name", typeof(string));
  8.     dt.Columns.Add("DateOfBirth", typeof(DateTime));
  9.  
  10.     //add rows of data
  11.     dt.Rows.Add(new object[] { 1, "Bugs Bunny", DateTime.Now});
  12.     dt.Rows.Add(new object[] { 2, "Daffy Duck", DateTime.Now });
  13.     dt.Rows.Add(new object[] { 3, "Scooby Doo", DateTime.Now });
  14.     return dt;        
  15. }

As can be seen, columns of type int, string and DateTime are added to the DataTable. Then, rows of data are added. This DataTable is later used for querying using Linq.

As mentioned earlier, to query DataTable using Linq, it has to be of type System.Collections.Generic.IEnumerable . To do this, DataTable’s AsEnumerable method can be used. This method converts the standard DataTable to a DataTable of IEnumerable type. The method for converting and querying the DataTable is below.

Query DataTable
  1. private void QueryDataTable(DataTable dt)
  2. {
  3.     var q = from DataRow row in dt.AsEnumerable()
  4.             select row;
  5.     
  6.     int col = dt.Columns.Count;//no of columns
  7.  
  8.     foreach (DataRow row in q)
  9.     {
  10.         for (int i = 0; i < col; i++)
  11.         {
  12.             L1.Text += row[i].ToString() + "&nbsp;";
  13.         }
  14.         L1.Text += "<br/>";
  15.     }
  16. }

At first, I have converted the DataTable to of type IEnumerable and have selected all the rows. Then, I have queried each of the DataRow and retrieved the values for each of the columns. L1 is a Literal control that has been declared on the aspx page.

Please note that, I have simply added the values returned in string variables, ideally, a System.Text.StringBuilder object should be used to achieve this.

The above methods can then be called from Page_Load or other methods as shown below.

Page_Load event
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.     QueryDataTable(GetDataTable());
  4. }

May 31, 2011

How to query an ArrayList with LINQ

In this example, I will show how to query an ArrayList using Linq. Since ArrayList are non-generic IEnumerable collections, the type of variable in the collection must be explicitly declared in the linq query.

I already have a web application setup, so, I will just add a class called Person. This is a very simple class containing only 2 properties – FirstName and LastName. The code for the class is below.

Person Class
  1. namespace WebApplication1.CSClass
  2. {
  3.     public class Person
  4.     {
  5.         public string FirstName { get; set; }
  6.         public string LastName { get; set; }
  7.  
  8.         public override string ToString()
  9.         {
  10.             return FirstName + " " + LastName;
  11.         }
  12.     }
  13. }

I will then add a web form where I will add an ArrayList, add Person objects to the collection and then query the collection using Linq. The code for this is below.

Query ArrayList with LINQ
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;
  7. using System.Collections;
  8. using WebApplication1.CSClass;
  9.  
  10. namespace WebApplication1
  11. {
  12.     public partial class LinqText : System.Web.UI.Page
  13.     {
  14.         protected void Page_Load(object sender, EventArgs e)
  15.         {
  16.             GetList();
  17.         }
  18.  
  19.         private void GetList()
  20.         {
  21.             ArrayList list = new ArrayList();
  22.             list.Add(new Person { FirstName = "Scooby", LastName="Doo" });
  23.             list.Add(new Person { FirstName = "Bugs", LastName = "Bunny" });
  24.             list.Add(new Person { FirstName = "Peter", LastName = "Pan" });
  25.  
  26.             var q = from Person p in list
  27.                     orderby p .FirstName
  28.                     orderby p.LastName
  29.                     select p;
  30.  
  31.             string br = "<br/>";
  32.             foreach (Person p in q)
  33.             {
  34.                 L1.Text += p.ToString() + br;
  35.             }
  36.  
  37.         }
  38.     }
  39. }

Note that, in the linq query, the object type is specified. The query will not work unless it is specified.

Reference: Shahed Kazi at AspNetify.com