Search code examples
c#arrayslinq

Concat/union 3 Array together in C#


i have a question how to concat or union 3 arrays in one line of the code? I've got Visual Studio 2015 and it looks like

int[] array1 = {1 ,2 ,3 ,-5 ,2 ,0 };
int[] array2 = {1 ,2 ,3 ,-1 ,5 ,0 };
int[] array3 = {1 ,2 ,3 ,-6 ,2 ,9 };

and i wanna on button click to have like:

Console.WriteLine(array1.Union(array2.Union(array3)).Where((x) => x >=0).Count)

Dunno rly how to Union 3 array in single line


Solution

  • The problem with your code is that after the Where clause the Count is a function and not a property.

    In addition a neater way will be to chain the Union instead. Also You can place the predicate in the Count instead:

    Console.WriteLine(array1.Union(array2).Union(array3).Count(x => x >= 0));
    

    To print only positive values of all arrays use string.Join:

    Console.WriteLine(string.Join(",", array1.Union(array2).Union(array3).Where(x => x >= 0)));
    //Prints: 1, 2, 3, 0, 5, 9