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<ClassA>
and idsToFind is IEnumerable<long>
.
LINQ Intersect operator is used to find common elements between two sequences (collections). Intersect opertor comes under Set operators category in LINQ Query operators. For example, we have two collections A = { 1, 2, 3 } and B = { 3, 4, 5 }. Intersect operator will find common elements in both sequences.
Firstly, set two lists. List<int> val1 = new List<int> { 25, 30, 40, 60, 80, 95, 110 }; List<int> val2 = new List<int> { 27, 35, 40, 75, 95, 100, 110 }; Now, use the Intersect() method to get the intersection between two lists.
CsharpProgrammingServer Side Programming. The Union method gets the unique elements from both the lists. Let us set two lists − var list1 = new List<int>{12, 65, 88, 45}; var list2 = new List<int>{40, 34, 65}; Now get the union of both the lists − var res = list1.Union(list2);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With