【问题标题】:how to add multiple items in list for a fix dictionary key如何在列表中添加多个项目以获取修复字典键
【发布时间】:2021-05-23 16:42:18
【问题描述】:

我有一个修复字典键X,我想用这个键X 创建一个List<Student> 作为finalResult,其中我有来自某个外部来源的data

在下面的代码中,我收到了错误,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
                }
            });
        }

【问题讨论】:

标签: c#


【解决方案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.
}

【讨论】:

    【解决方案2】:

    据我所见,您正在尝试将学生添加到分配给特定键的现有列表中,请尝试这样做:

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

    【讨论】:

      【解决方案3】:

      所以您想要字典中的单个元素,其中键设置为“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);
      

      【讨论】:

        猜你喜欢
        • 2013-07-09
        • 2017-09-17
        • 2020-07-14
        • 2021-02-17
        • 1970-01-01
        • 2019-02-08
        • 2018-09-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多