Home > OS >  How to convert a list of strings to an array of strings in C#
How to convert a list of strings to an array of strings in C#

Time:04-21

I know you can use the list.ToArray() method to convert, but I want to be able to access the individual characters of the string after conversion. For example, if the first element of the string list is "sgoth", once I convert it to a an array, I want to be able to access an individual element of the array like myArray[0,0] which would give me the first element of the first string. How would I accomplish this when converting from a list to an array?

CodePudding user response:

I think using jagged array would be better, but if you absolutely need to have array accessed with [,] as you decriped, you could do something following:

using System;
using System.Linq;
List<string> ListOfStrings = new List<string>() { "Test", "QWERTY" };
string[,] ArrOfStrings = new string[ListOfStrings.Count, ListOfStrings.Max(s => s.Length)];
for(int i = 0; i < ListOfStrings.Count; i  ){
    for(int j = 0; j < ListOfStrings[i].Length; j  ){
        ArrOfStrings[i,j] = ListOfStrings[i][j].ToString();   
    }
}
Console.WriteLine(ArrOfStrings[1,2]);

CodePudding user response:

You can do that by using the string indexer on each particular string in array, for example

var strList = new List<String>() { "foo", "boo" };

var strarr = strList.ToArray();

foreach (var str in strarr)
{
    Console.Write(str[0]);
}

Will print you "fb"

Or by using double indexer, for example you can access the first char of the first string like this:

Console.WriteLine(strarr[0][0]);

Will just print you "f"

CodePudding user response:

How would I accomplish this when converting from a list to an array?

It's perhaps most efficient to convert nothing

You have a List<string>, it can be accessed in a jagged fashion myArray[0][0] to get the first char of the first string, but you say you want to access it in multidim fashion, like myArray[0,0]..

..so you can make an adapter:

    public class MultiDimFlavoredJagged
    {
        List<string> _x;

        public MultiDimFlavoredJagged(List<string> x)
        {
            _x = x;
        }

        public char this[int x, int y] => _x[x][y];
    }

Now you can:

var j = new MultiDimFlavoredJagged(myArray);

var firstCharOfFirstString = j[0,0];

CodePudding user response:

//See example below;-

//Create a new list

List MyList = new List();

        //add elements to the list
        MyList.Add("Ade");
        MyList.Add("Raphael");
        MyList.Add("Bayo");
        MyList.Add("Paul");

        //creation of an array from the list
        string[] MyArray = MyList.ToArray();
  •  Tags:  
  • c#
  • Related