什么是此Linq查询等效的C#扩展方法?

时间:2010-11-22 22:58:38

标签: c# linq group-by extension-methods

this example:

public void Linq40()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

    var numberGroups =
        from n in numbers
        group n by n % 5 into g
        select new { Remainder = g.Key, Numbers = g };

    foreach (var g in numberGroups)
    {
        Console.WriteLine("Numbers with a remainder of {0} when divided by 5:",
            g.Remainder);

        foreach (var n in g.Numbers)
        {
            Console.WriteLine(n);
        }
    }
}

纯粹的c#等价物是什么?我明白了......

var numberGroups = numbers.GroupBy(n => n % 5)...

但是into条款有点神秘,我无法弄清楚如何从Key获取Select

2 个答案:

答案 0 :(得分:8)

numbers.GroupBy(n => n % 5).Select(g => new { Remainder = g.Key, Numbers = g });

答案 1 :(得分:8)

GroupBy返回IEnumerable<T> <IGrouping<TKey, TSource>。这样,您可以执行第二次Select操作,返回与上面完全相同的值:

var numberGroups = numbers.GroupBy(n => n % 5)
                          .Select(g => new { Remainder = g.Key, Numbers = g });