简体   繁体   中英

How to iterate over a multidimensional string array?

I have a 2d string array (at least I think it is called a 2d array):

var target = new string[var1,var2];

Now I want to convert it to List<List<string>> :

var listlist = new List<List<string>>();
foreach (var row in target)
{
  var newlist = new List<string>();
  foreach (var el in row)
  {
    newlist.Add(el);
  }
  listlist.Add(newlist);
}

But row has a type is string and el has type is char .

I can't understand why el is not a string ? What's wrong?

A foreach interates over a string[,] like it is a string[] . It doesn't split in rows.

If you do want to handle 'rows' and 'columns' those separately, you have to get the dimensions of the array, using the GetLength method:

var target = new string[var1, var2];

var listlist = new List<List<string>>();
for (int x = 0; x < target.GetLength(0); x++)
{
    var newlist = new List<string>();
    for (int y = 0; y < target.GetLength(1); y++)
    {
        newlist.Add(target[x, y]);
    }
    listlist.Add(newlist);
}

This is what you need

    static void SoStrList()
    {
        int var1=10, var2=7;
        var target=new string[var1, var2];

        var listlist=new List<List<string>>();

        for(int i=0; i<var1; i++)
        {
            var row=new List<string>();
            for(int j=0; j<var2; j++)
            {
                row.Add(target[i, j]);
            }
            listlist.Add(row);
        }
    }

use for loop instead of foreach

        var target = new string[2, 2];
        target[0, 0] = "a";
        target[0, 1] = "A";
        target[1, 0] = "b";
        target[1, 1] = "B";

        var listlist = new List<List<string>>();

        for (int i = 0; i < target.GetLength(0); i++)
        {
            var newlist = new List<string>();

            for (int j = 0; j < target.GetLength(1); j++)
                newlist.Add(target[i,j]);

            listlist.Add(newlist);
        }

Here:

foreach (var row in target)

You already have first element of your 2d array, and foreach take all chars of this elements

well ... string is array of chars. And this confusion is what you get from using keyword var for almost everything. Its not javascript.

Secondly : You need to go for something like this

for (int i = 0; i < target.GetLength(0); i++)
        {
            for (int y = 0; y < target.GetLength(1); y++)
            {
                your manipulation with strings
            }
        }

but srsly... get rid of vars !!!

For LINQ lovers, the same can be achieved using the following two lines:

int R = s.GetLength(0), C = s.GetLength(1);
var MyList = Enumerable.Range(0, R).Select(i => i * C).Select(i => s.Cast<string>.Skip(i).Take(C).ToList()).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM