繁体   English   中英

从CSV获取数据到字典C#

[英]Get data from csv to dictionary c#

我需要从csv到字典获取数据,但是当我尝试编译此代码时,我收到错误消息“已经添加了具有相同键的项。” 怎么做 ? `

   Dictionary<string, string> dic = new Dictionary<string, string>();

    public void AddToDic()
     {
         string line = "";
         using (StreamReader sr = new StreamReader(@"words.txt")) 
         {
              while (sr.Peek() != -1)
             {
                 line = line + sr.ReadLine();                
                 string[] splitted = line.Split(' ');
                 dic.Add(splitted[0], splitted[1]);  //ERROR An item with the same key has already been added.        
             }
          }

    }

    //text in words.txt is like: "car auto" newline "water voda" etc...

请尝试以下检查:

if(!dic.ContainsKey(splitted[0])
    dic.Add(splitted[0], splitted[1]);

由于您没有向我们显示您要解析的文件的内容,因此我们只能猜测。 这里是我的猜测(后面跟一个解决方案):

  • 文件的每一行包含两个单词
  • 第一个单词应成为字典的关键字
  • 该文件可能多次包含相同的关键字

因为一本字典,需要独特的密钥和文件可能包含同一个键​​多次有可能每个键多个值。 因此,更好的数据结构可能是: Dictionary<string, string[]>

您可以使用File.ReadLinesFile.ReadAllLines来读取文件的行,然后使用LINQ将其转换为字典:

Dictionary<string, string[]> result =
    File.ReadLines("words.txt")
        .Select(line => line.Split(' '))
        .GroupBy(arr => arr[0])
        .ToDictionary(gr => gr.Key,
                      gr => gr.Select(s => s[1]).ToArray());

说明:读取一行后,它被拆分为string[] 结果按第一个单词分组,第一个单词将成为字典的关键字。 每个组是一个IEnumerable<string[]>并且仅来自每个阵列的所述第二值被选择成的结果。

BTW:如果更换ReadLinesReadAllLines文件将立即被读取,然后它会在处理之前被关闭。 ReadLines读取各行,并在处理文件时使其保持打开状态。

字典键必须唯一

if(!dic.ContainsKey(splitted[0]))
   dic.Add(splitted[0], splitted[1]);  //ERROR An item with the same key 

将阻止错误的发生,但可能不会阻止您想要的行为。 想想你要如何处理重复键(失败文件的加载,只存储您看到的第一个关键,只存储最新的一个,你看,追加的键名的末尾一个计数器,如果有一个碰撞)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM