c# - linq to XML: unique attribute value count per group -
i have got xml nodes below.
... <parentnode> <node id="2343" name="some name" mode="some mode"> //some child nodes here </node> <node id="2344" name="some other name" mode="some mode"> //some child nodes here </node> ... </parentnode> <parentnode> <node id="2343" name="some name" mode="some other mode"> //some child nodes here </node> <node id="2344" name="some other name" mode="some mode"> //some child nodes here </node> </parentnode> .... what need
id name distinct-mode-count -------------------------------------------- 2343 name 2 2344 other name 1 i have tried below this.
xelement myxml = xelement.load(filepath); ienumberable<xelement> parentnodes = myxml.descendants("parentnode"); var nodeattributes = parentnodes.select(le => le.descendants("node") .groupby(x => new { id = x.attribute("id").value, name = x.attribute("name").value }).select(g => new { id = g.key.id, name = g.key.name, distinct_mode_count = // stuck })); i not sure how distinct_mode_count in above query.
edit
i need distinct attribute value count attribute "mode", regardless of parentnode in.
assuming want count of distinct "mode" attribute values within nodes same id/name, need project each element in group mode, take distinct sequence of modes, count it:
you need take count of group, , use selectmany "flatten" parent nodes. (or use myxml.descendants("node") start with.)
short complete example gives desired results:
using system; using system.collections.generic; using system.linq; using system.xml.linq; class test { static void main() { xelement myxml = xelement.load("test.xml"); ienumerable<xelement> parentnodes = myxml.descendants("parentnode"); var nodeattributes = parentnodes .selectmany(le => le.descendants("node")) .groupby(x => new { id = x.attribute("id").value, name = x.attribute("name").value }) .select(g => new { g.key.id, g.key.name, distinctmodecount = g.select(x => x.attribute("mode").value) .distinct() .count() }); foreach (var item in nodeattributes) { console.writeline(item); } } } alternatively:
xelement myxml = xelement.load("test.xml"); var nodeattributes = myxml .descendants("node") .groupby(...) // remaining code before
Comments
Post a Comment