Friday, 15 June 2012

c# - How to GroupBy/GroupJoin XElements using LINQ -


I have been killed with the query Please help me.

I have an XML

  & lt; Set type = "main" & gt; & Lt; FirstUnit xmlns: i = "http://www.w3.org/2001/XMLSchema-instance" z: id = "i1" xmlns: z = "http://schemas.microsoft.com/2003/10/ ordering / "& Gt; & Lt; CreateDate & gt; 2013-06-06T13: 19: 17.457 & lt; / CreateDate & gt; & Lt; PrimaryKey & gt; 1 & lt; / PrimaryKey & gt; & Lt; / FirstUnit & gt; & Lt; Secondinit xmlns: i = "http://www.w3.org/2001/XMLSchema-instance" z: id = "i1" xmlns: z = "http://schemas.microsoft.com/2003/10/ ordering / "& Gt; & Lt; CreateDate & gt; 2013-06-06T13: 19: 17.457 & lt; / CreateDate & gt; & Lt; PrimaryKey & gt; 1 & lt; / PrimaryKey & gt; & Lt; Exercise & gt; Test & lt; / Exercise & gt; & Lt; / SecondUnit & gt; & Lt; FirstUnit xmlns: i = "http://www.w3.org/2001/XMLSchema-instance" z: id = "i1" xmlns: z = "http://schemas.microsoft.com/2003/10/ ordering / "& Gt; & Lt; CreateDate & gt; 2013-06-06T13: 19: 17.457 & lt; / CreateDate & gt; & Lt; PrimaryKey & gt; 2 & lt; / PrimaryKey & gt; & Lt; / FirstUnit & gt; & Lt; Secondinit xmlns: i = "http://www.w3.org/2001/XMLSchema-instance" z: id = "i1" xmlns: z = "http://schemas.microsoft.com/2003/10/ ordering / "& Gt; & Lt; CreateDate & gt; 2013-06-06T13: 19: 17.457 & lt; / CreateDate & gt; & Lt; PrimaryKey & gt; 2 & lt; / PrimaryKey & gt; & Lt; Exercise & gt; Test & lt; / Exercise & gt; & Lt; / SecondUnit & gt; & Lt; / Set & gt;   

Now I want to group the unit based on the primary key which I want. I.e FirstUnit and SecondUnit in a group the primary key & gt; The node value should be "1" and the second group with the PrimaryKey node value "2".

I have tried to do it with the following question, yet it needs to be more refined,

  var element = xDocument.GroupBy (a => A.Elements () .Decundents (). Where (x => x.Name.LocalName == "Primary") .Oolist ());   

Thanks in advance.

It seems that you just need group by value Is:

  // If & lt; Set & gt; Document element, change the descendant ("Set") to the root level elements = xDocument.Descendants ("Set"). Elements () .GroupBy (x => x.Element ("PrimaryKey"));   

(If necessary, provide a namespace for the element - use a where the rule to check the local name is slightly ugly.) < / P>

If this does not work for you, please provide more information about what you are trying to do.

No comments:

Post a Comment