ChatGPT解决这个技术问题 Extra ChatGPT

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

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.

Also note you have DistinctBy in MoreLinq which will give you distinct MyClasss based on ID. Usage: var distincts = list.DistinctBy(x => x.ID);

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

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.
M
Maksim Vi.

Use the Distinct operator:

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

(minor naming point; it isn't a "list" of ids - it is a lazily evaluated IEnumerable - unless you call .ToList(), of course ;-p)
@Marc, a simple 2 line explantion of lazy eval? Please and thanks :D
@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.
P
Peter Mortensen

Using straight LINQ, with the Distinct() extension:

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

P
Peter Mortensen

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

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

P
Peter Mortensen
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


Doesnt answer the question, and even if it does, adds nothing new.