Reputation: 1277
I have two List<int>
say list1
and list2
.
Now I need to create a LINQ expression which should work in a way that for each item in list1, if it is available in list2 then store it in list3. For example, list1 contains {5, 10, 15}
and list2 contains {3, 5, 15, 20}
. Then with the help of LINQ, list3
should contain {5,15}. What I tried is -
list3 = list1.Where(t1 => list2.Any(t2 => t1.Contains(t2))).ToArray();
Upvotes: 1
Views: 400
Reputation: 45
list3 = (from p in list1 where list2.Contains(p) select p).ToList();
Upvotes: 0
Reputation: 29036
As like other answers stated, Intersect
will be a fine option for you, But i would like to fix the error in your code, Actually you should performs .Contains
operation in List2
not in elements of List2
. One more thing you have to note is that, the LHS of the assignment operation is of type List<int>
so you have to use .ToList()
instead for .ToArray()
. which means you have to wrote like this:
list3 = list1.Where(t1 => list2.Contains(t1)).ToList();
Or something like This:
list3 = list1.Where(t1 => list2.Any(x=> x == t1)).ToList();
Upvotes: 2