首页 > 解决方案 > 将数据从 csv 文件加载到键和值字典列表中

问题描述

我有一个包含如下文本列表的文件: 示例 csv 文件 csv 文件包含 3 列。第一列的长度始终为 5。所以我想遍历文件内容,将前 5 个字母存储为键,将剩余的列存储为值。我正在删除它们和 Substringing 之间的逗号,如下所示进行存储。

 static string line;
   static Dictionary<string, string> stations = new Dictionary<string, string>();

    static void Main(string[] args)
    {
       // Dictionary<string, List<KeyValuePair<string, string>>> stations = new Dictionary<string, List<KeyValuePair<string, string>>>();
        var lines = File.ReadAllLines(".\\ariba_sr_header_2017122816250.csv");

        foreach (var l in lines)
        {
            line = l.Replace(",", "");
            stations.Add(line.Substring(14),line.Substring(14, line.Length-14));

        }

        //read all key and value in file
        foreach (KeyValuePair<string, string> item in stations)
        {
            Console.WriteLine(item.Key);
            Console.WriteLine(item.Value);
        }
        Console.ReadLine();

    }

调试后,输出为 Output My Expected Result is below: Expected Result

标签: c#filedictionarykeyvaluepair

解决方案


干得好:

        var stations = new Dictionary<string, string>();
        var lines = File.ReadAllLines(@"C:\temp\22.txt");

        foreach (var l in lines)
        {
            var lsplit = l.Split(',');
            if (lsplit.Length > 1)
            {
                var newkey = lsplit[0];
                var newval = lsplit[1] + lsplit[2];
                stations[newkey] = newval;
            }
        }

        //read all key and value in file
        foreach (KeyValuePair<string, string> item in stations)
        {
            Console.WriteLine(item.Key + " = " + item.Value);
        }
        Console.ReadLine();

不完全是您期望的输出,但希望它有所帮助。


推荐阅读