0

如果我有这样的课程:

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 中的聚合每次都打败了我。

谢谢。

4

2 回答 2

2

我想这就是你想要的。我没有测试过,但应该是对的。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) 
    });
于 2013-07-04T11:26:57.070 回答
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)
               });
于 2013-07-04T11:40:07.517 回答