How do I use Linq to obtain a unique list of properties from a list of objects?
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!
IEnumerable<int> ids = list.Select(x=>x.ID).Distinct();
使用Distinct运算符:
var idList = yourList.Select(x=> x.ID).Distinct();
使用直接Linq和Distinct()
扩展:
var idList = (from x in yourList select x.ID).Distinct();
链接地址: http://www.djcxy.com/p/51360.html