WavyRancheros
WavyRancheros

Reputation: 121

LINQ - Output true/false "checklist" of items from list A contained in list B

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

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

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

Bal&#225;zs
Bal&#225;zs

Reputation: 2929

This is all it takes:

list1.Select(str => list2.Contains(str)).ToList();

Upvotes: 7

Related Questions