问题描述
我使用LINQ在C#中的工作,以XML和我需要做对我的XML节点的属性部分的排序。我的XML看起来是这样的。
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>
我可以使用排序依据子句中的XML进行排序,如
I can sort the xml using the orderby clause such as
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 the keys from query.
我想要做的就是让所有的债权集合1页,然后全部用2页等等说法,但我不知道是什么的最大页数即可。
What I want to do is get collections of all the claims with 1 page, then all the claims with 2 pages and so on, but I do not know what the maximum number of pages can be.
谁能帮助我?
编辑 -
我改变了我的intial思考如何做到这一点,我现在想提出类似于此的了。
I changed my intial thought on how to accomplish this and I now would like the out put to resemble this.
List<List<List<List<int>>>>
All claims
- 1 page
-zip1
-carr1
-int claim key
-int claim2 key
- car2
-zip2
-car1
- 2 pages
-zip1
等。诀窍是我需要查询的节点,并得到多个团体出来。可在我的发言这样做或者是一系列所需的报表?
and so on. The trick is I need to query the nodes and get multiple groups out of it. Can this be done in my statement or is a series of statements required?
推荐答案
您只需要添加一个 GROUPBY
子句:
You just need to add a GroupBy
clause:
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);
}
}
编辑:要获得名单,其中,名单,其中,INT&GT;&GT;
此,你会使用:
var claims = query.Select(group => group.Select(x => x.Key).ToList())
.ToList();
另外,如果你不需要CarrierZip和运营商的结果,可以简化查询和listifying为:
Alternatively, if you don't need the CarrierZip and Carrier in the results, you can simplify the query and the listifying to:
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();
这篇关于基于属性排序和分组XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!