Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersect LINQ query

Tags:

c#

.net

linq

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>.

like image 500
Klaus Nji Avatar asked Mar 04 '10 16:03

Klaus Nji


People also ask

How to use Intersect in LINQ?

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.

How to use Intersect in c#?

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.

What is Union C#?

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


1 Answers

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).

like image 89
SLaks Avatar answered Sep 17 '22 13:09

SLaks