Flatten an Array in C#

Naman picture Naman · Apr 9, 2016 · Viewed 13.8k times · Source

In C# what is the shortest code to flatten an array?

For example, I want

[[1,2],[2,3],[4,5]]

into the array

[1,2,3,4,5]

I am looking for the shortest way to do so.

Answer

devuxer picture devuxer · Apr 9, 2016

Maybe I'm reading "shortest code" the wrong way, but I would propose using LINQ SelectMany and Distinct:

var values = new[]
{
    new[] { 1, 2 },
    new[] { 2, 3 },
    new[] { 4, 5 },
};

var flattenedUniqueValues = values.SelectMany(x => x).Distinct();