C# 如何使用LINQ进行GroupBy/GroupJoin XElements

C# 如何使用LINQ进行GroupBy/GroupJoin XElements,c#,xml,linq,C#,Xml,Linq,我被一个疑问打动了。请帮帮我 我有一个xml <Set type="Main"> <FirstUnit xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/"> <CreateDate>2013-06-06T13:1

我被一个疑问打动了。请帮帮我

我有一个xml

      <Set type="Main">
          <FirstUnit xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
            <CreateDate>2013-06-06T13:19:17.457</CreateDate>
            <PrimaryKey>1</PrimaryKey>
          </FirstUnit>
          <Secondunit  xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
            <CreateDate>2013-06-06T13:19:17.457</CreateDate>
            <PrimaryKey>1</PrimaryKey>
            <Exercise>Test</Exercise>
          </SecondUnit>
          <FirstUnit xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
            <CreateDate>2013-06-06T13:19:17.457</CreateDate>
            <PrimaryKey>2</PrimaryKey>
          </FirstUnit>
          <Secondunit  xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
            <CreateDate>2013-06-06T13:19:17.457</CreateDate>
            <PrimaryKey>2</PrimaryKey>
            <Exercise>Test</Exercise>
          </SecondUnit>
     </Set>

提前感谢。

在我看来,您只需要根据这些元素的值进行分组:

// If <Set> is the document element, change Descendants("Set") to Root
var elements = xDocument.Descendants("Set")
                        .Elements()
                        .GroupBy(x => (int) x.Element("PrimaryKey"));
//如果是文档元素,则将子体(“Set”)更改为Root
var elements=xDocument.subjects(“Set”)
.要素()
.GroupBy(x=>(int)x.Element(“PrimaryKey”);
(必要时为元素提供名称空间-使用
Where
子句检查本地名称有点难看。)


如果这对您不起作用,请详细说明您正在尝试执行的操作。

谢谢您的快速回复Jon,我只是将输出作为列表,其中包含两项。一个人应该有第一个“第一单元”和“第二单元”。另一个应该有第二个“FirstUnit”和“SecondUnit”,基于主键
// If <Set> is the document element, change Descendants("Set") to Root
var elements = xDocument.Descendants("Set")
                        .Elements()
                        .GroupBy(x => (int) x.Element("PrimaryKey"));