How do I use LINQ to obtain a unique list of properties from a list of objects?

LinqClassListC# 3.0Properties

Linq Problem Overview


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.

Linq Solutions


Solution 1 - Linq

IEnumerable<int> ids = list.Select(x=>x.ID).Distinct();

Solution 2 - Linq

Use the Distinct operator:

var idList = yourList.Select(x=> x.ID).Distinct();

Solution 3 - Linq

Using straight LINQ, with the Distinct() extension:

var idList = (from x in yourList select x.ID).Distinct();

Solution 4 - Linq

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

Solution 5 - Linq

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();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmezoidView Question on Stackoverflow
Solution 1 - LinqMarc GravellView Answer on Stackoverflow
Solution 2 - LinqChristian C. SalvadóView Answer on Stackoverflow
Solution 3 - LinqDanaView Answer on Stackoverflow
Solution 4 - LinqBlack EagleView Answer on Stackoverflow
Solution 5 - LinqPergin SheniView Answer on Stackoverflow