7

I have a 2D string array. I want to convert this into

List<List<string>>

How do I achieve this in C#?

Rama
  • 1,019
  • 1
  • 15
  • 34

7 Answers7

10

Using Linq you could do this.

var result list.Cast<string>() 
            .Select((x,i)=> new {x, index = i/list.GetLength(1)})  // Use overloaded 'Select' and calculate row index.
            .GroupBy(x=>x.index)                                   // Group on Row index
            .Select(x=>x.Select(s=>s.x).ToList())                  // Create List for each group.  
            .ToList();

check this example

Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
5

Another way is to use the LINQ equivalent of a nested for loops:

string[,] array = { { "00", "01", "02"}, { "10", "11", "12" } };

var list = Enumerable.Range(0, array.GetLength(0))
    .Select(row => Enumerable.Range(0, array.GetLength(1))
    .Select(col => array[row, col]).ToList()).ToList();
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
4

I prefer Hari's answer, but if for some reason you have no access to Linq (.NET Framework < 3.5)

List<List<string>> lLString = new List<List<string>>();
string[,] stringArray2D = new string[3, 3] {
    { "a", "b", "c" }, 
    { "d", "e", "f" }, 
    { "g", "h", "i" }, 
};
for (int i = 0; i < stringArray2D.GetLength(0); i++) {
    List<string> temp = new List<string>();
    for (int j = 0; j < stringArray2D.GetLength(1); j++) { 
        temp.Add(stringArray2D[i,j]);
    }
    lLString.Add(temp);
}

The first loop iterates over rows, the next over columns. All columns (strings) are added to a single List<string> object which is then added to the parent List<List<string>> object upon exiting the inner loop.

I've included these on the off chance that by 2D array you actually mean a jagged array (non-rectangular). As this is an array of arrays you can simply access an inner array by its index and then call .ToList() on it.

List<List<string>> lLString = new List<List<string>>();
string[][] jaggedStringArray = new string[3][];
jaggedStringArray[0] = new string[] { "a", "b", "c" };
jaggedStringArray[1] = new string[] { "d", "e", "f", "g", "h" };
jaggedStringArray[2] = new string[] { "i" };
for (int i = 0; i < jaggedStringArray.Length; i++) {
    lLString.Add(jaggedStringArray[i].ToList());
}

If you're using a jagged array and do have .NET Framework >= 3.5, you can combine it with Linq like so

List<List<string>> lLString = jaggedStringArray.Select(x => x.ToList()).ToList();
2

Well, you could extend 2d array with custom generic ToList() method :

public static class ArrayHelper 
{
    public static List<List<T>> ToList<T>(this T[,] array)
    {
        var result = new List<List<T>>();
        var lengthX = array.GetLength(0);
        var lengthY = array.GetLength(1);

        // the reason why we get lengths of dimensions before looping through
        // is because we would like to use `List<T>(int length)` overload
        // this will prevent constant resizing of its underlying array and improve performance
        for(int i = 0; i < lengthX  i++)            
        {
            var listToAdd = new List<T>(lengthY);

            for(int i2 = 0; i2 < lengthY; i2++)
            {
                listToAdd.Add(array[i, i2]);
            }

            result.Add(listToAdd);
        }       

        return result;
    }       
}

And use it fairly simple with just one line of code :

public class Program
{   
    public static void Main()
    {
        int[,] array = new int[2,2] {{5,7},{9,14}};

        var result = array.ToList();        
    }
}
Fabjan
  • 13,506
  • 4
  • 25
  • 52
1

to generate the required list, can use this way:

  public static List<List<string>> GenerateListOfListOfStrings(string[,] result)
    {

        string[,] res = result;
        List<List<string>> listObj = new List<List<string>>();
        var list = new List<string>();
        foreach (var s in result)
        {
           list.Add(s);
        }
        listObj.Add(list);
        return listObj;
    }
error_handler
  • 1,191
  • 11
  • 19
0

From 2D array to list

double[,] d = new double[,]
{
    {1.0, 2.0},
    {3.0, 4.0},
    {5.0, 6.0},
    {7.0, 8.0},
    {9.0, 10.0}
};
List<double> lst = d.Cast<double>().ToList()

From 2D array to 2D List

2D array to 2D List

Community
  • 1
  • 1
Rachit Patel
  • 854
  • 5
  • 12
0

Use extensions.

    public static List<List<T>> Convert2dToList<T>(this T[][] array)
    {
        if (array == null) return null;
        List<List<T>> mainList = new List<List<T>>();
        for (int i = 0; i < array.Length; i++)
        {
            List<T> list = array[i].ToList();
            mainList.Add(list);
        }
        return mainList;
    }

Then call like this

    static void Main(string[] args)
    {
        int[][] list = new int[3][]
        {
            new int[]{ -2,-3,3 }, 
            new int[]{ -5,-10,1 },
            new int[]{ 10,30,-5 }
        };

        List<List<int>> A = list.Convert2dToList();
    }
Siddarth Kanted
  • 5,738
  • 1
  • 29
  • 20