views:

3667

answers:

4

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; }
}

What I want to do is 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.

Any help in creating an elegant solution would be much appreciated!

+15  A: 
IEnumerable<int> ids = list.Select(x=>x.ID).Distinct();
Marc Gravell
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
Definitely time well spent...
Marc Gravell
+3  A: 

Use the Distinct operator:

var idList = yourList.Select(x=> x.ID).Distinct();
CMS
(minor naming point; it isn't a "list" of ids - it is a lazily evaluated IEnumerable<int> - unless you call .ToList(), of course ;-p)
Marc Gravell
@Marc, a simple 2 line explantion of lazy eval? Please and thanks :D
masfenix
A: 

Using straight Linq, with the Distinct() extension: var idList = (from x in yourList select x.ID).Distinct();

Dana
A: 
        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

Black Eagle