0

I want to convert string[][] to List<List<string>>.

eg.

List<List<string>> listOfListReturned = new List<List<string>>();
string[][] twoDArrOfString = new string[2][];

I want to convert twoDArrOfString to listOfListReturned

Please suggest, how to do it?

Regards, Vivek

Lamloumi Afif
  • 8,941
  • 26
  • 98
  • 191
vivek jain
  • 591
  • 4
  • 13
  • 28

4 Answers4

5

Something like the following will also work:

string[][] twoDArrOfString = new string[2][];

var res = twoDArrOfString
    .Where(inner => inner != null) // Cope with uninitialised inner arrays.
    .Select(inner => inner.ToList()) // Project each inner array to a List<string>
    .ToList(); // Materialise the IEnumerable<List<string>> to List<List<string>>

You need to handle nulls if the inner arrays have not been initialised.

If you aren't going to enumerate through all of these, you might want to drop the final ToList and simply work against the IEnumerable<List<string>> to avoid resolving all inner lists if you don't need to (taking advantage of the deferred execution of enumerables).

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
1

Any reason in particular why you are doing this?

        List<List<string>> listOfListReturned = new List<List<string>>();
        string[][] twoDArrOfString = new string[2][];

        twoDArrOfString[0] = new[] {"a", "b"};
        twoDArrOfString[1] = new[] {"c", "d"};

        foreach (var s in twoDArrOfString)
        {
            listOfListReturned.Add(new List<string>(s));
        }

Or

        var result = twoDArrOfString.ToList();
        var listOfList = result.Select(x => x.ToList()).ToList();
Jun Wei Lee
  • 1,002
  • 11
  • 25
0

Not tested just imagine it :)

        for (int i = 0; i < twoDArrOfString.Length; i++)
        {
            for (int j = 0; j < twoDArrOfString[i].Length; j++)
            {
                listOfListReturned[i].Add(twoDArrOfString[j].ToString());
            }
            listOfListReturned.Add(listOfListReturned[i]);
        }
0

A more linq-ish version might be

List<List<string>> listOfListReturned = new List<List<string>>()
    {
        new List<string> {"A", "B"},
        new List<string> {"C", "D"},
    };

string[][] twoDArrOfString = new string[2][]
    {
        new [] {"A", "B"},
        new []{"C", "D"},
    };

var actual = twoDArrOfString.Select(arr => new List<string>(arr)).ToList();

for (var idx = 0; idx < listOfListReturned.Count; idx++) {
    CollectionAssert.AreEqual(listOfListReturned[idx], actual[idx]);
}

EDIT: Adam's solution above allowing for empty rows is better.

AlanT
  • 3,627
  • 20
  • 28