我有一个Foo的列表。 Foo具有BarLum属性。一些FooBar值相同。如何使用lambda/linq按FooBar进行分组,以便可以遍历每个分组的Lum

最佳答案

Deeno

享受:

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

10-07 16:32