Ivan
Ivan

Reputation: 64207

How to get a column of a 2D array in C#?

var array = new[] {new[]{'a', 'b', 'c'}, new[]{'d', 'e', 'f'}, new[]{'g', 'h', 'i'}};

var column = // should be like new[]{'b', 'e', 'h'} given index 1

How to do this?

Of course I could create a new list, populate it manually iterating through all the lines in a loop and convert it to an array but Isn't there a more laconic way?

Upvotes: 2

Views: 481

Answers (2)

Selman Genç
Selman Genç

Reputation: 101680

You can write an extension method for that:

public static T[] GetColumn<T>(this T[][] source, int columnIndex)
{
    int length = source.Length;

    var values = new T[length];
    for (int i = 0; i < length; i++)
    {
         if(source[i].Length > columnIndex)
            values[i] = source[i][columnIndex];
    }

    return values;
}

Then :

var column = array.GetColumn(1);

This also doesn't throw an IndexOutOfRange exception if one of your arrays contains less element than column number.

Upvotes: 0

Fede
Fede

Reputation: 44028

LINQ is your friend.

It's what separates us C# developers from the mere mortals.

var array = new[] { new[] { "a", "b", "c" }, new[] { "d", "e", "f" }, new[] { "g", "h", "i" } };

var col1 = array.Select(x => x[1]);

//col1 contains "b", "e" and "h"

Upvotes: 3

Related Questions