189

I'm trying to use LINQ to return a list of ids given a list of objects where the id is a property. I'd like to be able to do this without looping through each object and pulling out the unique ids that I find.

I have a list of objects of type MyClass and one of the properties of this class is an ID.

public class MyClass
{
  public int ID { get; set; }
}

I want to write a LINQ query to return me a list of those Ids.

How do I do that, given an IList<MyClass> such that it returns an IEnumerable<int> of the ids?

I'm sure it must be possible to do it in one or two lines using LINQ rather than looping through each item in the MyClass list and adding the unique values into a list.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mezoid
  • 28,090
  • 37
  • 107
  • 148
  • 3
    Also note you have `DistinctBy` in [MoreLinq](https://code.google.com/p/morelinq/) which will give you distinct `MyClass`s based on `ID`. Usage: `var distincts = list.DistinctBy(x => x.ID);` – nawfal Nov 29 '13 at 08:02

5 Answers5

350
IEnumerable<int> ids = list.Select(x=>x.ID).Distinct();
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    Wow! I thought it was something simple...I just couldn't think of it. Looks like I'm going to have to spend some more time familiarizing myself with Linq. – mezoid Feb 20 '09 at 05:13
30

Use the Distinct operator:

var idList = yourList.Select(x=> x.ID).Distinct();
Maksim Vi.
  • 9,107
  • 12
  • 59
  • 85
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • 6
    (minor naming point; it isn't a "list" of ids - it is a lazily evaluated IEnumerable - unless you call .ToList(), of course ;-p) – Marc Gravell Feb 20 '09 at 05:11
  • @Marc, a simple 2 line explantion of lazy eval? Please and thanks :D – masfenix Jun 30 '10 at 22:03
  • 3
    @masfenix Lazy eval means the operation is not done until it is actually used. In this case, the selecting the IDs and choosing only the distinct ones is not necessarily done when the statement in this answer is executed. It will be done when you actually start to traverse through the idList, for example in a foreach loop. – Mark Meuer Dec 30 '14 at 18:58
13

Using straight LINQ, with the Distinct() extension:

var idList = (from x in yourList select x.ID).Distinct();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dana
  • 354
  • 2
  • 9
2
int[] numbers = {1,2,3,4,5,3,6,4,7,8,9,1,0 };
var nonRepeats = (from n in numbers select n).Distinct();

foreach (var d in nonRepeats)
{

    Response.Write(d);
}

Output

1234567890

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Black Eagle
  • 1,107
  • 2
  • 11
  • 18
2

When taking Distinct, we have to cast into IEnumerable too. If the list is <T> model, it means you need to write code like this:

 IEnumerable<T> ids = list.Select(x => x).Distinct();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pergin Sheni
  • 393
  • 2
  • 11