Find the intersection of two lists in 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?
Solution 1:
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.
Solution 2:
You can use Intersect:
var a = new List<int>();
var b = new List<int>();
var c = a.Intersect(b);
Solution 3:
Produce a list c
containing all elements that are present in both lists a
and b
:
List<int> c = a.Intersect(b).ToList();