I have list of int A,B. i like to do the following step in linq
list c = new List();
for (int i = 0; i < a.count; i++)
{
for (i
You can use Intersect:
var a = new List<int>();
var b = new List<int>();
var c = a.Intersect(b);
Produce a list c
containing all elements that are present in both lists a
and b
:
List<int> c = a.Intersect(b).ToList();
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.
The LINQ equivalent of your code is:
var c = from i in Enumerable.Range(0, a.Count)
from j in Enumerable.Range(0, b.Count)
where a[i] == b[j]
select a[i];
var cList = c.ToList();
But it's much nicer to do:
var c = from aItem in a
join bItem in b on aItem equals bItem
select aItem;
var cList = c.ToList();
But this doesn't filter duplicates. To filter duplicates completely, you can do:
var cList = a.Intersect(b).ToList();
If you want duplicates to show up as many times as they do in b
, for example:
var aSet = new HashSet<int>(a);
var cList = b.Where(aSet.Contains)
.ToList();
As Chris mentions in his comment on the original question, the sample code provided will return duplicates in list c (see his comment for details). Intersect will only return distinct values. To duplicate the behavior of the original sample code, try this:
var c = (from value in a
where b.Contains(a)
select a);
This is my version of intersection:
var a = new List<int>();
var b = new List<int>();
// intersection
var c = a.Where(x => b.Any(y => x == y)).ToList();