XML data sorting in Linq

Ranjeet_8
Posted by Ranjeet_8 under LINQ category on | Points: 40 | Views : 2097
XML File :

<Employee>
<Employee Ecode="001" Ename="EEEE" />
<Employee Ecode="001" Ename="CCCC" />
<Employee Ecode="001" Ename="AAAA" />
<Employee Ecode="001" Ename="DDDD" />
<Employee Ecode="001" Ename="BBBB" />
</Employee>

Below is the C# Code in Linq

static void Main(string[] args)
{
XElement xelement = XElement.Load("..\\..\\Employee.xml");
var dictNm = (from element in xelement.Descendants("Employee")
let Epname = (string)element.Attribute("Ename")
orderby Epname
select new
{
EmpID = element.Attribute("Ecode").Value,
EmpName = Epname
})
.ToDictionary(c => c.EmpID , c => c.EmpName);

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


Output will be :
AAAA
BBBB
CCCC
DDDD
EEEE

Comments or Responses

Posted by: Netgrid on: 10/30/2012 Level:Starter | Status: [Member] | Points: 10
XML example is below:-
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
<Employee>
<EmpId>1</EmpId>
<Name>Sam</Name>
<Sex>Male</Sex>
<Phone Type="Home">423-555-0124</Phone>
<Phone Type="Work">424-555-0545</Phone>
<Address>
<Street>7A Cox Street</Street>
<City>Acampo</City>
<State>CA</State>
<Zip>95220</Zip>
<Country>USA</Country>
</Address>
</Employee>
<Employee>
<EmpId>2</EmpId>
<Name>Lucy</Name>
<Sex>Female</Sex>
<Phone Type="Home">143-555-0763</Phone>
<Phone Type="Work">434-555-0567</Phone>
<Address>
<Street>Jess Bay</Street>
<City>Alta</City>
<State>CA</State>
<Zip>95701</Zip>
<Country>USA</Country>
</Address>
</Employee>
<Employee>
<EmpId>3</EmpId>
<Name>Kate</Name>
<Sex>Female</Sex>
<Phone Type="Home">166-555-0231</Phone>
<Phone Type="Work">233-555-0442</Phone>
<Address>
<Street>23 Boxen Street</Street>
<City>Milford</City>
<State>CA</State>
<Zip>96121</Zip>
<Country>USA</Country>
</Address>
</Employee>
<Employee>
<EmpId>4</EmpId>
<Name>Chris</Name>
<Sex>Male</Sex>
<Phone Type="Home">564-555-0122</Phone>
<Phone Type="Work">442-555-0154</Phone>
<Address>
<Street>124 Kutbay</Street>
<City>Montara</City>
<State>CA</State>
<Zip>94037</Zip>
<Country>USA</Country>
</Address>
</Employee>
</Employees>
dapfor. com

Login to post response