我有Foo
的列表。 Foo具有属性Bar
和Lum
。某些Foo
具有Bar
的相同值。如何使用lambda / linq按Foo
对Bar
进行分组,以便我可以遍历每个分组的Lum
?
答案 0 :(得分:4)
var q = from x in list
group x by x.Bar into g
select g;
foreach (var group in q)
{
Console.WriteLine("Group " + group.Key);
foreach (var item in group)
{
Console.WriteLine(item.Bar);
}
}
答案 1 :(得分:3)
享受:
var foos = new List<Foo> {
new Foo{Bar = 1,Lum = 1},
new Foo{Bar = 1,Lum = 2},
new Foo{Bar = 2,Lum = 3},
};
// Using language integrated queries:
var q = from foo in foos
group foo by foo.Bar into groupedFoos
let lums = from fooGroup in groupedFoos
select fooGroup.Lum
select new { Bar = groupedFoos.Key, Lums = lums };
// Using lambdas
var q = foos.GroupBy(x => x.Bar).
Select(y => new {Bar = y.Key, Lums = y.Select(z => z.Lum)});
foreach (var group in q)
{
Console.WriteLine("Lums for Bar#" + group.Bar);
foreach (var lum in group.Lums)
{
Console.WriteLine(lum);
}
}
要了解有关LINQ阅读101 LINQ Samples
的更多信息