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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: