DotNetCurry Logo

Sort Items in an XML file using LINQToXML and Load it in a Dictionary

Posted by: Suprotim Agarwal , on 3/16/2010, in Category LINQ
Views: 79898
Abstract: I was recently working on a requirement where I had to read a XML file and then identify a key, value pair and load it into a Dictionary object. I used LINQToXML to solve this requirement.
Sort Items in an XML file using LINQToXML and Load it in a Dictionary
 
I was recently working on a requirement where I had to read a XML file and then identify a key, value pair and load it into a Dictionary object. I used LINQToXML to solve this requirement. I assume that you are familiar with LINQ to XML. If that is not the case, I would recommend you to get some hands-on on LINQ to XML. These three articles will help you out:
We will use a sample file called ‘Employees.xml’ for demonstration purpose.
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
 <Employee EmpId="1'" Name="Sam" />
 <Employee EmpId="2" Name="Lucy"/>
 <Employee EmpId="3" Name="Kate"/>
 <Employee EmpId="4" Name="Chris"/>
 <Employee EmpId="5" Name="David"/>
 <Employee EmpId="6" Name="Zolar"/>
 <Employee EmpId="7" Name="Shannon"/>
</Employees>
 
In this example, we will read the Employee data from the XML file, sort it by name and then load it into a Dictionary. The ‘EmployeeID’ will act as a Key and ‘Name’ as the Value for the Dictionary. I assume that each EmpId is unique here.
Here’s the code to perform this task.
C#
static void Main(string[] args)
{
    XElement xelement = XElement.Load("..\\..\\Employees.xml");
 
    var empDict = (from element in xelement.Descendants("Employee")
                      let name = (string)element.Attribute("Name")
                      orderby name                   
                      select new
                      {
                          EmployeeID = element.Attribute("EmpId").Value,
                          EmployeeName = name
                      })
           .ToDictionary(a => a.EmployeeID, a => a.EmployeeName);
 
    Console.ReadLine();
}
 
VB.NET (Converted using tool)
Shared Sub Main(ByVal args() As String)
      Dim xelement As XElement = XElement.Load("..\..\Employees.xml")
 
      Dim empDict = ( _
          From element In xelement.Descendants("Employee") _
          Let name = CStr(element.Attribute("Name")) _
          Order By name _
          Select New With {Key .EmployeeID = element.Attribute("EmpId").Value, Key .EmployeeName = name}).ToDictionary(Function(a) a.EmployeeID, Function(a) a.EmployeeName)
 
      Console.ReadLine()
 
End Sub
In the code shown above, we sort the list by Name and then use the .toDictionary() to create a Dictionary<(Of <(TKey, TValue>)>).
Here’s a screenshot of the code in debug mode with the sorted Dictionary
Dictionary
The entire source code of this article can be downloaded over here. I hope you liked the article and I thank you for viewing it.
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by hai on Monday, January 28, 2013 2:41 AM
can u provide the above code with out using xml values in the logic

thanks in advance