Reputation: 121
I have two lists:
List<string> list1 = new List<string>(){ "a", "b", "c", "d" };
List<string> list2 = new List<string>(){ "b", "d", "e" };
I want to find all items of list1 that match the items in list2, and generate a List list3 that contains:
{ false, true, false, true }
How can I go about that?
Thanks in advance, Wavy
Upvotes: 1
Views: 333
Reputation: 236268
@Balazs answer is correct, but you should know that Contains
operation on list is O(n) operation. And if lists are pretty big, then creating new list will be O(n*m) operation, which might be pretty slow. If you want to check whether some value is among other values, best way is having some hash-based structure which has O(1) for Contains
operation. So, just put second list values to HashSet
var hashSet = new HashSet<string>(list2);
var result = list1.Select(hashSet.Contains).ToList();
Upvotes: 2
Reputation: 2929
This is all it takes:
list1.Select(str => list2.Contains(str)).ToList();
Upvotes: 7