tags:

views:

744

answers:

4

If I have an IEnumerable where ClassA exposes an ID property of type long. Is it possible to use a Linq query to get all instances of ClassA with ID belonging to a second IEnumerable?

In other words, can this be done?

IEnumerable<ClassA> = original.Intersect(idsToFind....)?

where original is an IEnumerable and idsToFind is IEnumerable.

TIA.

+1  A: 

Use the Where method to filter the results:

var result = original.Where(o => idsToFind.Contains(o.ID));
Ahmad Mageed
+1  A: 

A simple way would be:

IEnumerable<ClassA> result = original.Where(a => idsToFind.contains(a.ID));
bruno conde
+1  A: 

You can do it, but in the current form, you'd want to use the Where extension method.

var results = original.Where(x => yourEnumerable.Contains(x.ID));

Intersect on the other hand will find elements that are in both IEnumerable's. If you are looking for just a list of ID's, you can do the following which takes advantage of Intersect

var ids = original.Select(x => x.ID).Intersect(yourEnumerable);
David Pfeffer
+3  A: 

Yes.

As other people have answered, you can use Where, but it will be extremely inefficient for large sets.

If performance is a concern, you can call Join:

var results = original.Join(idsToFind, o => o.Id, id => id, (o, id) => o);

If idsToFind can contain duplicates, you'll need to either call Distinct() on the IDs or on the results or replace Join with GroupJoin (The parameters to `GroupJoin would be the same).

SLaks
I was going to refer this also. +1
bruno conde
This is what I was looking for, thank you. Somehow, this did not make it in my original quesion but idsToFind = IEnumerable<long>.Thanks again.
e28Makaveli