Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the intersection of two lists in linq?

Tags:

c#

linq

I have list of int A,B. i like to do the following step in linq

list<int> c = new List<int>();  for (int i = 0; i < a.count; i++) {     for (int j = 0; j < b.count; j++)     {         if (a[i] == b[j])         {             c.add(a[i]);         }     } } 

if its a and b is object , I need check particular properties like this manner and add list if it equals how can i do this in linq?

like image 401
ratty Avatar asked Feb 21 '11 11:02

ratty


People also ask

How to Intersect two lists in linq?

eg a = {1,2,2,3} and b = {2,2,4,6} will give c = {2,2,2,2}. Is this what you want or are your lists unique anyway so its not important? I ask just because the obvious linq answer will give c={2,2} as that is the intersection of the lists.

How to find intersection of two lists 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.

How to use Intersect in linq c#?

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.

What does Intersect do in c#?

Intersect returns the common elements of both entities and returns the result as a new entity. For example, there are two lists, the first list contains 1, 2 and 3 the and second list contains 3, 5 and 6. Then the intersect operator will return 3 as the result because 3 exists in both lists.


2 Answers

You could use the Intersect method:

var c = a.Intersect(b); 

This return all values both in a and b. However, position of the item in the list isn't taken into account.

like image 138
Femaref Avatar answered Sep 18 '22 09:09

Femaref


You can use Intersect:

var a = new List<int>(); var b = new List<int>();  var c = a.Intersect(b); 
like image 40
Klaus Byskov Pedersen Avatar answered Sep 21 '22 09:09

Klaus Byskov Pedersen