Sorting and Grouping XML Based on Attributes
I am working with LINQ to XML in C # and I need to do some sorting on the attributes of my xml nodes. My xml looks something like this.
<root>
<Claim key="1" carrier="carA" zip="34343" pages="1"/>
<Claim key="2" carrier="carA" zip="34343" pages="2"/>
<Claim key="3" carrier="carB" zip="34343" pages="4"/>
</root>
I can sort the xml using an orderby clause like
var query= from claim in root.Elements("Claim")
let Key = claim.Attributes("Key").First().Value
let Carrier = claim.Attributes("Carrier").First().Value
let CarrierZip = int.Parse(claim.Attributes("CarrierZip").First().Value)
let Pages = claim.Attributes("Pages").First().Value
orderby Pages ascending, CarrierZip ascending, Carrier ascending
select claim;
Then I get a list of keys from the request.
What I want to do is collect collections of all 1 page claims, then all 2 page claims and so on, but I don't know how many the maximum number of pages can be.
can anyone help me?
EDIT -
I changed my inner thought on how to do this and now I would like it to be like this.
List<List<List<List<int>>>>
All claims
- 1 page
-zip1
-carr1
-int claim key
-int claim2 key
- car2
-zip2
-car1
- 2 pages
-zip1
etc. The trick is that I need to query nodes and get multiple groups from it. Can this be done in my application or is a series of statements required?
source to share
You just need to add a sentence GroupBy
:
var query= from claim in root.Elements("Claim")
let Key = claim.Attributes("Key").First().Value
let Carrier = claim.Attributes("Carrier").First().Value
let CarrierZip = int.Parse(claim.Attributes("CarrierZip").First().Value)
let Pages = claim.Attributes("Pages").First().Value
orderby Pages ascending, CarrierZip ascending, Carrier ascending
group new { CarrierZip, Carrier, Key } by Pages;
foreach (var group in query)
{
Console.WriteLine("Claims with {0} pages:", group.Key);
foreach (var entry in group)
{
Console.WriteLine(" {0} {1} {2}", entry.CarrierZip, entry.Carrier,
entry.Key);
}
}
EDIT: To get List<List<int>>
from this you have to use:
var claims = query.Select(group => group.Select(x => x.Key).ToList())
.ToList();
Alternatively, if you don't need CarrierZip and Carrier in the results, you can simplify your query and list:
var query= from claim in root.Elements("Claim")
let Key = claim.Attributes("Key").First().Value
let Carrier = claim.Attributes("Carrier").First().Value
let CarrierZip = int.Parse(claim.Attributes("CarrierZip").First().Value)
let Pages = claim.Attributes("Pages").First().Value
orderby Pages ascending, CarrierZip ascending, Carrier ascending
group Key by Pages;
var claims = query.Select(group => group.ToList())
.ToList();
source to share