【问题标题】:How to split() a delimited string to a List<String>如何将分隔字符串拆分()到 List<String>
【发布时间】:2012-03-05 01:00:52
【问题描述】:

我有这个代码:

    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'

【问题讨论】:

    标签: c# .net list arraylist


    【解决方案1】:

    任意使用:

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

    或来自 LINQ:

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

    或者改变你的代码不依赖具体的实现:

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

    【讨论】:

      【解决方案2】:

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

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

      请注意,您需要导入System.Linq 才能访问.ToList() 函数。

      【讨论】:

      • 这里可能应该提到你必须使用命名空间 System.Linq
      • @sairfan listStrLineElements = line?.Split(',').ToList();
      【解决方案3】:
      string[] thisArray = myString.Split('/');//<string1/string2/string3/--->     
      List<string> myList = new List<string>(); //make a new string list    
      myList.AddRange(thisArray);    
      

      使用AddRange传递string[],得到一个字符串列表。

      【讨论】:

        【解决方案4】:

        包括使用命名空间System.Linq

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

        您可以轻松地使用它来遍历每个项目。

        foreach(string str in stringList)
        {
        
        }
        

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

        【讨论】:

          【解决方案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;
              }
          

          【讨论】:

            【解决方案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
            

            【讨论】:

              【解决方案7】:

              试试这条线:

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

              【讨论】:

                【解决方案8】:

                我使用这种扩展方法来处理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”,我们希望去掉逗号后的空格。

                【讨论】:

                  【解决方案9】:

                  你可以这样使用 var countryDBs="myDB,ukDB";

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

                          foreach (var countryDB in countryDBsList)
                          {
                             
                          }
                  

                  【讨论】:

                    猜你喜欢
                    • 2012-10-17
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2011-04-04
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多