-1

我有一个修复字典键X,我想List<Student>用这个键创建一个,X就像finalResultdata从一些外部来源获得的一样。

在下面的代码中,我收到错误,An item with the same key has already been added. Key: X'. 如何解决?

 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
                }
            });
        }
4

3 回答 3

1

从我所看到的情况来看,您正在尝试将学生添加到分配给特定键的现有列表中,请尝试执行以下操作:

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
    });
}
于 2021-05-23T17:07:45.173 回答
1

您可以通过以下两种方式之一执行此操作。

  1. 首先创建您的列表并将其添加到字典中一次。
  2. 检查密钥是否已经存在。如果没有,添加它,否则更新列表。

首先创建列表。

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

添加/更新具有相同键的字典。

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.
}
于 2021-05-23T17:10:53.260 回答
0

所以你想要字典中的单个元素,键设置为“X”,值设置为学生列表?

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);
于 2021-05-23T17:22:33.350 回答