How to split() a delimited string to a List

前端 未结 7 2327
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 11:30

I had this code:

    String[] lineElements;       
    . . .
    try
    {
        using (StreamReader sr = new StreamReader(\"TestFile.txt\"))
        {
            


        
7条回答
  •  天命终不由人
    2020-12-04 12:18

    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> LoadCsvAsDictionary(string path)
        {
            var result = new List>();
    
            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 columns = null;
            while ((line = file.ReadLine()) != null)
            {
                var values = SplitCsv(line);
                if (n == 0)
                {
                    columns = values;
                }
                else
                {
                    var dict = new Dictionary();
                    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 SplitCsv(string csv)
        {
            var values = new List();
    
            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;
        }
    

提交回复
热议问题