Is it possible to combine these two statements into one which returns "contains" and "not contains" results?
string[] words = { "one", "two", "three", "four" };
int[] numbers = { 4, 5, 6 };
string[] contains =
(from w in words
where numbers.Contains(w.Length)
select w).ToArray();
string[] notContains =
(from w in words
where !numbers.Contains(w.Length)
select w).ToArray();
You can do:
var groups = words.GroupBy(w => numbers.Contains(w.Length));
This will return at most two groups: one with the key false
and one with the key true
.
As vc 74 pointed out in the comments, numbers.Contains
is an O(n) operation when numbers
is an array. Converting it to a HashSet instead will make this a constant time operation, which is asymptotically much faster.
So, here's the updated code:
var numberHS = new HashSet<int>(numbers);
var groups = words.GroupBy(w => numberHS.Contains(w.Length));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With