开发者

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

开发者 https://www.devze.com 2023-04-03 03:56 出处:网络
I\'m using LINQ to XML. This is the line which I\'m having problems: var objectives = (from c in xdoc.Descendents(\"Condition\")

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

精彩评论

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