Search code examples
c#linqlinq-group

Understanding overloads of GroupBy in Linq


i was going through linq GroupBy extension method and stumbled on one of the overloads which got me confused, now this will yield an result like this

 int[] numbers = {1,1,1,2,2,3,4,4,4,4,4,5,5 };
            var result = numbers.GroupBy(g => g).Select(s => new {
                key=s.Key,
                data=s
            });

enter image description here

but my question is, how to use other overloads, for instance this

enter image description here

how can i use this overload, i have searched many blogs but no blogs explain me all the overloads


Solution

  • The elementSelector lets you project the elements (your numbers).

    int[] numbers = {1,1,1,2,2,3,4,4,4,4,4,5,5 };
    var result = numbers.GroupBy(g => g, i => 2 * i); // project each number to the doubled value
    

    resulting in

    3 times 2    (2 * 1)
    2 times 4    (2 * 2)
    1 time  6    (2 * 3)
    5 times 8    (2 * 4)
    2 times 10   (2 * 5)
    

    I personally prefer the overload taking a resultSelector over the extra call to Select:

    int[] numbers = {1,1,1,2,2,3,4,4,4,4,4,5,5 };
    var result = numbers.GroupBy(g => g, (key, g) => new {
        key,
        data=g
     });
    

    The resultSelector is equivalent to the subsequent Select call in your example, but it takes the key and the sequence of elemetns for that key as separate parameters, while Select works on the resulting IGrouping<>.