开发者

How to get another specified attribute using grouping by from LINQ to XML

I'm using LINQ to XML.

This is the line which I'm having problems:

var objectives = (from c in xdoc.Descendents("Condition")
                  group c by (int)c.Attribute("ObjectiveID") into k
                  select k).ToDictionary(e=> e.Key, // HERE I MUST PUT ANOTHER ATTRIBUTE FROM c)

开发者_JAVA技巧Where I put the comment, I need to get another attribute (c.Attribute("Objective")). But I can't access to c properties and get that one.


A grouping may contain more than one item per group. A dictionary on the other hand can only contain one value for each key. You probably want ToLookup() which does allow an enumeration of values for each key:

var objectives = (from c in xdoc.Descendents("Condition")
                  group c by (int)c.Attribute("ObjectiveID") into k
                  select k).ToLookup(e=> e.Key, e => e.Select( x=> x.Objective));

If you do want to use a dictionary you can just pick i.e. the first item of each grouping:

var objectives = (from c in xdoc.Descendents("Condition")
                  group c by (int)c.Attribute("ObjectiveID") into k
                  select k).ToDictionary(e=> e.Key, e => e.First().Objective));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜