How to split() a delimited string to a List<String>

C#.NetListArraylist

C# Problem Overview


I had this code:

    String[] lineElements;       
    . . .
    try
    {
        using (StreamReader sr = new StreamReader("TestFile.txt"))
        {
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                lineElements = line.Split(',');
                . . .

but then thought I should maybe go with a List instead. But this code:

    List<String> listStrLineElements;
    . . .
    try
    {
        using (StreamReader sr = new StreamReader("TestFile.txt"))
        {
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                listStrLineElements = line.Split(',');
. . .

...gives me, "Cannot implicitly convert type 'string[]' to 'System.Collections.Generic.List'"

C# Solutions


Solution 1 - C#

string.Split() returns an array - you can convert it to a list using ToList():

listStrLineElements = line.Split(',').ToList();

Note that you need to import System.Linq to access the .ToList() function.

Solution 2 - C#

Either use:

List<string> list = new List<string>(array);

or from LINQ:

List<string> list = array.ToList();

Or change your code to not rely on the specific implementation:

IList<string> list = array; // string[] implements IList<string>

Solution 3 - C#

Include using namespace System.Linq

List<string> stringList = line.Split(',').ToList();

you can make use of it with ease for iterating through each item.

foreach(string str in stringList)
{

}

String.Split() returns an array, hence convert it to a list using ToList()

Solution 4 - C#

Just u can use with using System.Linq;

List<string> stringList = line.Split(',')     // this is array
 .ToList();     // this is a list which you can loop in all split string

Solution 5 - C#

Try this line:

List<string> stringList = line.Split(',').ToList(); 

Solution 6 - C#

This will read a csv file and it includes a csv line splitter that handles double quotes and it can read even if excel has it open.

    public List<Dictionary<string, string>> LoadCsvAsDictionary(string path)
    {
        var result = new List<Dictionary<string, string>>();

        var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        System.IO.StreamReader file = new System.IO.StreamReader(fs);

        string line;

        int n = 0;
        List<string> columns = null;
        while ((line = file.ReadLine()) != null)
        {
            var values = SplitCsv(line);
            if (n == 0)
            {
                columns = values;
            }
            else
            {
                var dict = new Dictionary<string, string>();
                for (int i = 0; i < columns.Count; i++)
                    if (i < values.Count)
                        dict.Add(columns[i], values[i]);
                result.Add(dict);
            }
            n++;
        }

        file.Close();
        return result;
    }

    private List<string> SplitCsv(string csv)
    {
        var values = new List<string>();

        int last = -1;
        bool inQuotes = false;

        int n = 0;
        while (n < csv.Length)
        {
            switch (csv[n])
            {
                case '"':
                    inQuotes = !inQuotes;
                    break;
                case ',':
                    if (!inQuotes)
                    {
                        values.Add(csv.Substring(last + 1, (n - last)).Trim(' ', ','));
                        last = n;
                    }
                    break;
            }
            n++;
        }

        if (last != csv.Length - 1)
            values.Add(csv.Substring(last + 1).Trim());

        return values;
    }

Solution 7 - C#

string[] thisArray = myString.Split('/');//<string1/string2/string3/--->     
List<string> myList = new List<string>(); //make a new string list    
myList.AddRange(thisArray);    

Use AddRange to pass string[] and get a string list.

Solution 8 - C#

I use this extension method which handles null input and also removes the redundant white spaces.

public static List<string> CsvToList(this string csv)
{
    if (string.IsNullOrEmpty(csv))
    {
        return new List<string>();
    }

    return csv.Split(',').Select(item => item.Trim()).ToList();
}

Note that if the input CSV is: "Apple, Orange, Pear" we want to get rid of the white spaces after the commas.

Solution 9 - C#

You can use like this var countryDBs="myDB,ukDB";

var countryDBsList = countryDBs.Split(',').ToList();

        foreach (var countryDB in countryDBsList)
        {
           
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionB. Clay Shannon-B. Crow RavenView Question on Stackoverflow
Solution 1 - C#BrokenGlassView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#GaurravsView Answer on Stackoverflow
Solution 4 - C#sonertbncView Answer on Stackoverflow
Solution 5 - C#user2342244View Answer on Stackoverflow
Solution 6 - C#Brian RiceView Answer on Stackoverflow
Solution 7 - C#Anuja WadatkarView Answer on Stackoverflow
Solution 8 - C#Hooman BahreiniView Answer on Stackoverflow
Solution 9 - C#Manoj TyagiView Answer on Stackoverflow