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

No comments:

Post a Comment