In LINQ how do I select one item per ID?

c#, linq

Solution

Use `GroupBy` and `First` method combination:

var results = source.GroupBy(x => x.Id).Select(g => g.First()).ToList();

Or as a syntax-based query:

var results = (from i in source
               group i by i.Id into g
               select g.First()).ToList();

Problem

This may be obvious but I am having trouble getting my head around it. I have a list of items eg: ``` BOB 5 Brian 5 Sam 6 James 7 Emily 8 Sandra 8 Michael 8 ``` These are in a `List<MyObject>` I want to filter the list so there is only 1 item per ID, by selecting the first one with a unique ID. I should end up with ``` BOB 5 Sam 6 James 7 Emily 8 ``` I am having trouble working out a clean way to do this. Any ideas?

Original source

Related problems