Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Use the Distinct operator:

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

Using straight LINQ, with the Distinct() extension:

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

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

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