Suppose I have this LINQ query (on .NET 4.0) :
IEnumerable<Service> listService = (from MyObject myObj in new MyObjects()
select myObj.Services);
As you can see, listService is a collection of “collection” (Services is a collection of “Service”, which contains a Title, an ID (what I need), and some other fields.).
What I’d like to do in LINQ is to have, with that query, an IEnumerable<int>, with the Distinct list of ID for each Service for each Services.
Is there a way to do this on LINQ or I need to cycle with some foreach and manage with another arrays?
Example :
my first myObj (so, MyObjects[0]) have got a collection, called Service, which contain single Service. Every Service have got a single id, respectively : "1", "2", "4"
my second myObj (so, MyObjects[1]) have got a collection, called Service, which contain single Service. Every Service have got a single id, respectively : "4", "5", "1", "2"}
What I need is a “single” collection which contains the list of ID from each Service collection from each myObj. This list must be with Distinct value.
Since you haven’t shown the content of your classes, I implemented what I could guess from your description. Does this match your objects?
If so, then if I stick the following in the constructor for
MyObjects:I can get the distinct IDs like so:
The following test program:
prints: