【问题标题】:Linq: aggregate results by group nameLinq:按组名聚合结果
【发布时间】:2013-07-02 09:07:58
【问题描述】:

如果我有这样的课程:

public class Foo
{
  public string Category {get;set;}
  public IEnumerable<Bar> Bars {get;set};
}

我有一个这样的 Foos 集合:

foo1: { Category = "Amazing", Bars = /* some Bars */ }
foo2: { Category = "Amazing", Bars = /* some Bars */ }
foo3: { Category = "Extraordinary", Bars = /* some Bars */ }

我如何将它聚合成一个新的 2 个 Foo 集合,如下所示:

foo4: { Category = "Amazing", Bars = /* all the Bars from foo1 and foo2 because both of them have the category "Amazing" */ }
foo5: { Category = "Extraordinary", Bars = /* some Bars */ }

抱歉,如果我没有用正确的语言解释这一点。 Linq 中的聚合每次都让我失望。

谢谢。

【问题讨论】:

    标签: c# linq aggregation


    【解决方案1】:

    我想这就是你想要的。我没有测试过,但应该是对的。 GroupBy 返回由 Category 键入的组的新枚举。 SelectMany 将多个可枚举项扁平化为一个可枚举项。

    var foos = your list of foos;
    var groupedFoos = foos
        .GroupBy(f => f.Category)
        .Select(g => new Foo
        { 
            Category = g.Key, 
            Bars = g.SelectMany(f => f.Bars) 
        });
    

    【讨论】:

    • 更新了我的答案。 SelectMany 没有读取 Bars 属性。
    • 就是这样!谢谢,那会花我几个小时的时间。
    • 欢迎您!我建议你阅读一下 LINQ 可以做什么,它非常强大,而且...可爱!
    【解决方案2】:

    检查一下:

    var data = (from f in foos               
                   group f by f.Category into fgroup
                   select new
                   {
                       Category = fgroup.Key,
                       Bars = fgroup.SelectMany(x => (IEnumerable<Bar>)x.Bars)
                   });
    

    【讨论】:

      猜你喜欢
      • 2010-11-20
      • 2019-05-02
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 2019-08-01
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      相关资源
      最近更新 更多