简体   繁体   中英

Get data from csv to dictionary c#

I need to get data from csv to dictionary but when i try to compile this code i recieve error "An item with the same key has already been added." How to do it ? `

   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...

Try below checking:

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

Since you don't show us the contents of the file you are trying to parse we can only guess. Here are my guesses (followed by a solution):

  • each line of the file contains two words
  • the first word should become the key of a dictionary
  • the file may contain the same key word multiple times

Since a dictionary requires unique keys and the file may contain the same key multiple times there can be multiple values for each key. So a better data structure might be: Dictionary<string, string[]> .

You can use File.ReadLines or File.ReadAllLines to read the lines of a file and then use LINQ to transform that into a dictionary:

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

Explanation: After reading a line it is splitted into a string[] . The result is grouped by the first word which will become the key for the dictionary. Each group is an IEnumerable<string[]> and only the second value from each array is selected into the result.

BTW: If you replace ReadLines with ReadAllLines the file will be read at once and then it will be closed before processing it. ReadLines reads the lines one by one and keeps the file open during processing it.

Dictionaries keys must be unique

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

will stop the error from happening, but probably not the behavior you want. Think about how you want to handle duplicate keys (fail loading of the file, only store the key of the first one you see, only store the latest one you see, append a counter on the end of the key name if there's a collision)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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