Linq:按组名汇总结果

时间:2013-07-04 11:19:29

标签: c# linq aggregation

如果我有这样的课程:

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个Foos的新集合,如下所示:

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的聚合每次都让我失望。

感谢。

2 个答案:

答案 0 :(得分:2)

我认为这就是你想要的。我还没有测试过,但应该是正确的。 GroupBy返回按类别键入的新的枚举组。 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) 
    });

答案 1 :(得分:0)

检查一下:

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)
               });