如何在内存列表中分组?

时间:2008-09-05 16:01:36

标签: c# .net linq lambda

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

2 个答案:

答案 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)

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

的更多信息