我有一个清单Foo
。Foo 具有属性Bar
和Lum
. 一些Foo
s 具有相同的值Bar
。如何使用 lambda/linq 对我Foo
的 s进行分组,Bar
以便遍历每个分组的Lum
s?
Deeno
问问题
332 次
2 回答
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);
}
}
于 2008-09-05T16:06:29.527 回答
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 示例
于 2008-09-06T07:34:15.007 回答