Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to define a List<> of two elements string array?

I want to build two-dimentional array of strings where length of one dimention is 2. Similar to this

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

Doing

List<string[]> list = new List<string[]>();

list.Add(new string[2] {"a", "b"});
list.Add(new string[2] {"c", "d"});
list.Add(new string[2] {"e", "f"});
list.Add(new string[2] {"g", "h"});

list.ToArray();

gives me

string[][]

but not

string[,] 

array.

Just curious, is there some trick to build dynamically

string[,] 

array somehow?

like image 241
Alexander Prokofyev Avatar asked Nov 13 '08 07:11

Alexander Prokofyev


2 Answers

You can do this.

List<KeyValuePair<string, string>>

The idea being that the Key Value Pair would mimic the array of strings you replicated.

like image 142
Terrence Avatar answered Sep 28 '22 06:09

Terrence


Well, you could reasonably easily write an extension method to do it. Something like this (only tested very slightly):

public static T[,] ToRectangularArray<T>(this IEnumerable<T[]> source)
{
    if (!source.Any())
    {
        return new T[0,0];
    }

    int width = source.First().Length;
    if (source.Any(array => array.Length != width))
    {
         throw new ArgumentException("All elements must have the same length");
    }

    T[,] ret = new T[source.Count(), width];
    int row = 0;
    foreach (T[] array in source)
    {
       for (int col=0; col < width; col++)
       {
           ret[row, col] = array[col];
       }
       row++;
    }
    return ret;
}

It's a slight shame that the above code uses T[] as the element type. Due to generic invariance I can't currently make source IEnumerable<IEnumerable<T>> which would be nice. An alternative might be to introduce a new type parameter with a constraint:

public static T[,] ToRectangularArray<T,U>(this IEnumerable<U> source)
    where U : IEnumerable<T>

Somewhat hairy, but it should work. (Obviously the implementation needs some changes too, but the basic principle is the same.)

like image 21
Jon Skeet Avatar answered Sep 28 '22 07:09

Jon Skeet