【问题标题】:Group by clause limiting items per groupGroup by 子句限制每组的项目
【发布时间】:2013-12-09 10:58:06
【问题描述】:

我有以下 XML:

<R N="1">
  <MT N="Section" V="Section-1" />
  <MT N="Person" V="John" />
</R>
<R N="2">
  <MT N="Section" V="Section-1" />
  <MT N="Person" V="Peter" />
</R>
<R N="3">
  <MT N="Section" V="Section-2" />
  <MT N="Person" V="Joseph" />
</R>
... ...

<R N="N">
  <MT N="Section" V="Section-J" />
  <MT N="Person" V="PersonX" />
</R>

以及以下生成IEnumerable&lt;IGrouping&lt;string,XElement&gt;&gt;GroupBy 子句:

var something = MyElements.GroupBy
(
   x => x.Elements("MT")
   .First
   (
       type => type.Attribute("N").Value == "Section"
   )
   .Attribute("V").Value
   ,
   x=>x
);

我希望每组最多包含 4 个项目。

我不能对表达式x=&gt;x 使用Take 方法,因为它不是IEnumerable&lt;T&gt;

你知道如何限制每个组的结果吗?

【问题讨论】:

  • 你能描述一下你想从xml中选择什么数据吗?看起来您的查询不是您可以使用的最佳查询

标签: c# .net linq lambda linq-to-xml


【解决方案1】:

如果你想要的只是IEnumerable&lt;IEnumerable&lt;XElement&gt;&gt;,你可以像这样使用Take

var something = MyElements.GroupBy
(
   x => x.Elements("MT")
   .First
   (
       type => type.Attribute("N").Value == "Section"
   )
   .Attribute("V").Value
   ,
   x => x,
   (Key, Items) => Items.Take(4)
);

如果你也需要密钥,你可以这样做:

var something = MyElements.GroupBy
(
   x => x.Elements("MT")
   .First
   (
       type => type.Attribute("N").Value == "Section"
   )
   .Attribute("V").Value
   ,
   x => x,
   (Key, Items) => new { Key, Items = g.Take(4) }
);

尽管如此,你会得到一个匿名类型的IEnumerable。您需要遍历 Items 集合。如果您不能使用匿名类型(例如,您需要将其作为方法签名的一部分),您始终可以创建自己的结果类型或使用 Tuple

【讨论】:

  • +1 用于GroupBy 重载,带有结果选择器(可读性值得怀疑,但那是单个运算符调用)
  • 是的,在我的应用程序中,我需要 Key 来呈现组和里面的所有项目。匿名项目非常适合,非常感谢。
【解决方案2】:

我相信您可以使用以下声明式查询来获得所需的内容

var xdoc = XDocument.Load(path_to_xml);
var query = from r in xdoc.Descendants("R")
            let section = r.Elements("MT")
                           .First(mt => (string)mt.Attribute("N") == "Section")
                           .Attribute("V")
            group r by (string)section into g
            select g.Take(4);

【讨论】:

    猜你喜欢
    • 2015-05-28
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    相关资源
    最近更新 更多