如何将分隔的字符串拆分为List<String>?

208

我有这段代码:

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

但后来我想也许应该使用列表。 但是这段代码:

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

...给出了这个错误信息:"无法隐式将类型'string[]'转换为'System.Collections.Generic.List'"

9个回答

462

string.Split()返回一个数组 - 您可以使用ToList()将其转换为列表:

listStrLineElements = line.Split(',').ToList();
请注意,您需要导入 System.Linq 以访问 .ToList() 函数。

78
需要翻译的内容:Probably should mention here that you have to be using namespace System.Linq。建议在这里提到,您必须使用命名空间System.Linq。 - Dr. Cogent
4
sairfan,将line字符串按逗号分隔并转换为列表类型的操作。 - Vinigas

71

可以使用以下方法之一:

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

或者来自于 LINQ:

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

或者修改您的代码,不要依赖特定的实现:

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

16

使用 System.Linq 命名空间

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

你可以轻松地利用它来遍历每个项目。

foreach(string str in stringList)
{

}

String.Split()返回一个数组,因此可以使用ToList()将其转换为列表


6

试试这行代码:

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

6

你只需要使用using System.Linq;

,即可实现。

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

5
这段代码将读取一个csv文件,其中包括一个csv行分隔符,可以处理双引号,即使Excel打开了该文件也能读取。
    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;
    }

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

使用AddRange方法传递string[]参数并获取一个字符串列表。


3

我使用这个扩展方法,它可以处理null输入,并且还可以去除多余的空格

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

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

请注意,如果输入的CSV是:"Apple, Orange, Pear",我们希望去掉逗号后的空格。

3
你可以像这样使用: var countryDBs="myDB,ukDB"; var countryDBsList = countryDBs.Split(',').ToList();
        foreach (var countryDB in countryDBsList)
        {
           
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接