January 10, 2011

LINQ to XML Sorting




In this post, we will read data from the XML file using LINQ to XML, sort it by an element and then load it into a Dictionary.

If you are new to LINQ to XML, check my article LINQ To XML Tutorials with Examples

The sample XML file looks like this:

Let us see how to read this XML file and list the customer names alphabetically. Add a reference to System.XML.Linq in your console application and use this code

static void Main(string[] args)
{
XElement xelement = XElement.Load("..\\..\\Customers.xml");

var dict = (from element in xelement.Descendants("Customer")
let name = (string)element.Attribute("Name")
orderby name
select new
{
CustID = element.Attribute("CustId").Value,
CustName = name
})
.ToDictionary(c => c.CustID, c => c.CustName);

foreach (var item in dict)
{
Console.WriteLine(item.Value);
}

Console.ReadLine();
}

As shown above, we first sort the list by Customer Name and then use the .toDictionary() to create a Dictionary<(Of <(TKey, TValue>)>). We then loop through the Dictionary and print the sorted names.

OUTPUT



Giving me +1 tells me you liked this article! Thanks in advance


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "LINQ to XML Sorting"
 

Copyright © 2009-2013 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions