0

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

Lijin Durairaj
  • 4,910
  • 15
  • 52
  • 85
  • 4
    Have you tried reading the docs ? https://msdn.microsoft.com/en-us/library/system.linq.enumerable.groupby(v=vs.110).aspx. – Titian Cernicova-Dragomir Jan 03 '18 at 15:57
  • The documentation *does* explain what each overload does. You can save a *lot * of time if you check the docs before googling for blog posts. In your case it's [GroupBy(Func,Func)](https://msdn.microsoft.com/en-us/library/bb534304(v=vs.110).aspx). If you had objects with properties instead of integers, you could use the element selector to return a single property or calculated value instead of the entire object. – Panagiotis Kanavos Jan 03 '18 at 16:01
  • @PanagiotisKanavos The docs is useful as a reference. It is a technical explanation with a lot of jargon. If you don't understand the purpose/jargon at all, this explanation will also be difficult to understand. For a higher level overview, blogs can be more helpful – Burak Mar 29 '21 at 16:52

1 Answers1

3

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<>.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
  • 1
    @IvanStoev fixed it, just missed that the `resultSelector` needs the key _and_ the sequence of elements for this key as parameters. – René Vogt Jan 03 '18 at 16:14