Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return two arrays using one WHERE statement

Tags:

arrays

c#

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();
like image 581
Aleksey Pavlov Avatar asked Dec 07 '22 15:12

Aleksey Pavlov


1 Answers

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.

Edit

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));
like image 146
Cristian Lupascu Avatar answered Dec 10 '22 05:12

Cristian Lupascu