-1

I have a fix dictionary key X and I want to create a List<Student> with this key X as finalResult where I have data from some external source.

In below code I am getting error, An item with the same key has already been added. Key: X'. How to fix it?

 const string dictKey = "X";
        var finalResult = new Dictionary<string, List<Student>>();

        var data = new Dictionary<string, int> {{"A1!D1", 10}, {"A2!D2", 20}};

        foreach (var (key, value) in data)
        {
            finalResult.Add(dictKey, new List<Student>
            {
                new Student
                {
                    Name = key.Split('!')[0],
                    Section = key.Split('!')[1],
                    Age = value
                }
            });
        }
user584018
  • 10,186
  • 15
  • 74
  • 160
  • Does this answer your question? [how to check if object already exists in a list](https://stackoverflow.com/questions/3435089/how-to-check-if-object-already-exists-in-a-list) – Mark Schultheiss May 23 '21 at 16:44
  • I can check if key exist or not, but how to add items in list in both case? – user584018 May 23 '21 at 16:46
  • 1
    Does this answer your question? [c# dictionary one key many values](https://stackoverflow.com/questions/2101069/c-sharp-dictionary-one-key-many-values) – Wyck May 23 '21 at 16:46
  • https://stackoverflow.com/q/2829873/125981 also – Mark Schultheiss May 23 '21 at 16:46
  • 2
    Note you have hard coded `dictKey` so it will only ever have `X` value -dictionary keys must be unique. Please clarify what your dictionary keys must derive from – Mark Schultheiss May 23 '21 at 16:51
  • I have other `dictkey` and against each I need to add one or more students. Here for simplicity I took one `dictkey` – user584018 May 23 '21 at 16:56
  • @user584018: that doesn't make sense. Your exception is clear: _"An item with the same key has already been added. Key: X'"_ This is your hard coded `dictKey`, so it seems that you are always using it, as in your code. If that's not the actual code and not the actual exception, edit your question. – Tim Schmelter May 23 '21 at 17:22

3 Answers3

1

From what I am seeing, you are trying to add students to existing lists, which are assigned to specific keys, try doing this:

const string dictKey = "X";

var finalResult = new Dictionary<string, List<Student>>();

var data = new Dictionary<string, int> {{"A1!D1", 10}, {"A2!D2", 20}};

foreach (var (key, value) in data)
{
    // check if key exists in the dictionary, and return the list assigned to it if it does
    if (!finalResult.TryGetValue(dictKey, out var list))
    {
        // if the key doesn't exist we assign a new List<Student> to the variable "list"
        list = new List<Student>();

        // We Add it to the dictionary, now when we call TryGetValue(dictKey) it will return true and the resulting value will be the List<Student> we assigned to "list".
        finalResult.Add(dictKey, list);
    }
    // Add the student to the list.
    list.Add(new Student
    {
        Name = key.Split('!')[0],
        Section = key.Split('!')[1],
        Age = value
    });
}
Space
  • 175
  • 9
1

You can do this one of the two ways.

  1. Create your List first and add it to the dictionary one time.
  2. Check if the key already exists. if not, add it, otherwise update the list.

Create List first.

var data = new Dictionary<string, int> { { "A1!D1", 10 }, { "A2!D2", 20 } };
List<Student> allStudents = data.Select(x => new Student()
{
    Name = x.Key.Split('!')[0],
    Section = x.Key.Split('!')[1],
    Age = x.Value
}).ToList(); // Need to convert to List from IEnumerable.

finalResult.Add(dictKey, allStudents);

Add / Update dictionary with same key.

var data = new Dictionary<string, int> { { "A1!D1", 10 }, { "A2!D2", 20 } };
foreach (var (key, value) in data)
{
    // Create Student object first otherwise repeating code twice.
    var student = new Student
    {
        Name = key.Split('!')[0],
        Section = key.Split('!')[1],
        Age = value
    };

    if (!finalResult.ContainsKey(dictKey))
        finalResult.Add(dictKey, new List<Student> { student }); // new list
    else
        finalResult[dictKey].Add(student); // Adding new item to existing list.
}
Jawad
  • 11,028
  • 3
  • 24
  • 37
0

So you want a single element in the dictionary with the key being set to "X" and the value set to the list of students?

var students = data
    .Select(d => new Student
    {
        Name = d.Key.Split('!')[0],
        Section = d.Key.Split('!')[1],
        Age = d.Value
    })
    .ToList();

finalResult.Add(dictKey, students);
umberto-petrov
  • 731
  • 4
  • 8