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: 82696
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
Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on .NET Standard and the upcoming C# 8.0 too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Purchase this eBook at a Discounted Price!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

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 The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for ten consecutive times. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



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

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook