Erik Lenstrup Erik Lenstrup - 2 months ago 11
C# Question

Same key has already been added then trying to name rows

In my conversion program I am using a dictionary to gives names to specific rows read from a pre defined text file. Then creating a multidimensional array named "Rows" an error occurs:


An item with the same key has already been added.


The following piece of code is written:

Dictionary<string, int> rows = new Dictionary<string, int>();

// The file "read.txt" is being read
string[] lines = File.ReadAllLines("read.txt");

int[] array = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

// In this section each line is being read and the spacing is removed

foreach (string s in lines)
{
string[] arr = s.Split(' '); // This line ables the program to differ between variables and numbers.

for (int i = 0; i < arr.Length; i++)
{
array[i] = Convert.ToInt32(arr[i]); // arr is now converted into a Int.

rows.Add("array" + i, array[i]);

}
}


Then debugging the error occurs then the loop is ended. Why does the error appear and how do I fix it?

Answer

You probably want to associate multiple int's to the key in the dictionary. A Dictionary won't do for this, but rather a

Dictionary<string, List<int>>  or   Dictionary<string, HashSet<int>>

If you are using ("array" + i) as key, an int would do it.

Initializing an array with many 0's is not very nice, rather use new int[n].

With these small changes, here is my updated version:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StackOverflow
{
  class Program
  {
    static void Main(string[] args)
    {
        Dictionary<string, HashSet<int>> rows = new Dictionary<string, HashSet<int>>();

        // The file "read.txt" is being read 
        string[] lines = new string[] { "1", "2", "1 2"};  //File.ReadAllLines("read.txt");

        // In this section each line is being read and the spacing is removed 
        foreach (string s in lines)
        {
            string[] arr = s.Split(' '); // This line ables the program to differ between variables and numbers. 

            int[] array = new int[arr.Length];
            for (int i = 0; i < arr.Length; i++)
            {
                array[i] = Convert.ToInt32(arr[i]); // arr is now converted into a Int.

                string key = "array" + i;
                if (!rows.ContainsKey(key)) rows.Add(key, new HashSet<int>());
                rows[key].Add(array[i]);
            }
        }

        foreach (string key in rows.Keys)
        {
            Console.WriteLine($"{key}: {String.Join(", ", rows[key])}");
        }
    }
  }
}

Many further improvements are possible.

Comments