将csv文件中的数据加载到键和值字典列表中

时间:2018-07-19 10:11:27

标签: c# file dictionary keyvaluepair

我有一个文件,其中包含一个文本列表,如下所示: Example csv file 那里的csv文件包含3列。第一列的长度始终为5。因此,我想遍历文件内容,将前5个字母存储为Key,将其余的列存储为value。我要删除它们和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 我的预期结果如下: Expected Result

2 个答案:

答案 0 :(得分:0)

我在这里看不到任何KeyValuePair。你有

 00021,00014,Ordered
 00021,00026,Ordered
 00024,00036,Ordered
 ...

您想要

 00021
 00021
 00024
 000014Ordered 
 000026Ordered
 000036Ordered 
 ...

结果似乎是IEnumerable<string>。您可以尝试使用 Linq

var result = File
  .ReadLines(".\\ariba_sr_header_2017122816250.csv")
  .Line(line => line.Split(','))
  .SelectMany(items => new string[] {
     items[0],
    $"0{items[1]}{items[2]}" })
  .OrderBy(item => item.Length);

foreach (var item in result)
  Console.WriteLine(item);

在这里,我们将Split的每一行像00021,00014,Ordered放入单独的items中:{00021,00014,有序} anf then combine them back with a help of SelectMany`。我们要

  1. 00021,即items[0]
  2. 000014Ordered,即0 + items[1] + items[2]

最后,我们想先放空物品-OrderBy(item => item.Length)

答案 1 :(得分:0)

您在这里:

        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();

与您期望的输出不完全相同,但希望它会有所帮助。

相关问题