0

I have this code similar to this post

List<MyObject> myList = new List<MyObject>(){new MyObject { Number1 = 1, Number2 = 2, Number3 = 3 },
                                             new MyObject { Number1 = 1, Number2 = 2, Number3 = 3 }};

var listWithoutDuplicated = myList
    .GroupBy(x => new { x.Number1, x.Number2, x.Number3 })
    .Select(x => x.First());

int counter = 0;
foreach (var item in listWithoutDuplicated)
{
    counter ++;
} 

That code would return counter = 1, so it works fine, but why is it necessary .Select(x => x.First()); and not only .First(); at the end?

// This code would not remove duplicates.
var listWithoutDuplicated = myList
    .GroupBy(x => new { x.Number1, x.Number2, x.Number3 })
    .First();

Thanks a lot.

Community
  • 1
  • 1
Coyolero
  • 2,353
  • 4
  • 25
  • 34

1 Answers1

3

.First() returns the first group from a sequence of groups.

Select(group => group.First()) takes a sequences of groups and returns a new sequence representing the first item in each group.

Both are entirely valid things to do, and also extremely different. You can see this by simply printing out the results, or for that matter, just looking at the type of the result (this would be more visible in the code if you did not usevar).

Servy
  • 202,030
  • 26
  • 332
  • 449