Intersect LINQ query
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);
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).
I will post an answer using Intersect
.
This is useful if you want to intersect 2 IEnumerables
of the same type.
First we will need an EqualityComparer
:
public class KeyEqualityComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, object> keyExtractor;
public KeyEqualityComparer(Func<T, object> keyExtractor)
{
this.keyExtractor = keyExtractor;
}
public bool Equals(T x, T y)
{
return this.keyExtractor(x).Equals(this.keyExtractor(y));
}
public int GetHashCode(T obj)
{
return this.keyExtractor(obj).GetHashCode();
}
}
Secondly we apply the KeyEqualityComparer
to the Intersect
function:
var list3= list1.Intersect(list2, new KeyEqualityComparer<ClassToCompare>(s => s.Id));