Linq分组加入

时间:2013-04-09 19:46:56

标签: linq join left-join linq-group

我正在构建一些使用Linq对象的XML,并使用类似于以下示例的代码设法获得我想要的内容。我不禁觉得它可能会更好。真正困扰我的是“插图”节点,我必须将该组加入原始数据。

你可以通过运行查询来查看我正在尝试做的事情(我使用过Linqpad)。有一个页面列表,其中一些有插图。如果有的话,我想列出所有带插图的页面。

请评论..?

var illustrations = new []
{
    new {page = 1, illustration= "a"}, 
    new {page = 2, illustration = "b"}, 
    new {page = 1, illustration = "c"}
};
var pages = new []
{
    new {page = 1, pageName = "w"}, 
    new {page = 2, pageName = "x"}, 
    new {page = 3, pageName = "y"}, 
    new {page = 4, pageName = "z"}
};


var x1 = new XElement("contents",
    from page in pages join illustration in illustrations on page.page equals illustration.page
    into pagesIllustrations from pr in pagesIllustrations.DefaultIfEmpty()  //Left outer join
    group page by page.page into g
    select new XElement("content",
        new XAttribute("contentPageName", g.First().pageName),
        new XElement("pages", 
            from o1 in g.Distinct()
            select new XElement("page",
                new XAttribute("PageNumber", o1.page),
                new XAttribute("PageName", o1.pageName))),
        new XElement("illustrations", 
            from o2 in g.Distinct() join i in illustrations on o2.page equals i.page
            select new XElement("illustration", 
                new XAttribute("PageNumber", i.page), 
                new XAttribute("IllustrationName", i.illustration)))));

x1.Dump();

这是我正在制作的xml。这正是我想要的,我不禁感到我不是最好的方式。

<contents>
  <content contentFileName="w">
    <pages>
      <page PageNumber="1" PageName="w" />
    </pages>
    <resources>
      <resource PageNumber="1" ResourceName="a" />
      <resource PageNumber="1" ResourceName="c" />
    </resources>
  </content>
  <content contentFileName="x">
    <pages>
      <page PageNumber="2" PageName="x" />
    </pages>
    <resources>
      <resource PageNumber="2" ResourceName="b" />
    </resources>
  </content>
  <content contentFileName="y">
    <pages>
      <page PageNumber="3" PageName="y" />
    </pages>
    <resources />
  </content>
  <content contentFileName="z">
    <pages>
      <page PageNumber="4" PageName="z" />
    </pages>
    <resources />
  </content>
</contents>

0 个答案:

没有答案