Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在列表中为修复字典键添加多个项_C# - Fatal编程技术网

C# 如何在列表中为修复字典键添加多个项

C# 如何在列表中为修复字典键添加多个项,c#,C#,我有一个固定的字典键X,我想用这个键X作为finalResult创建一个列表,其中我有一些外部源的数据 在下面的代码中,我遇到了一个错误,已经添加了一个具有相同密钥的项。键:X'。如何修复它 const string dictKey = "X"; var finalResult = new Dictionary<string, List<Student>>(); var data = new Dictionary&l

我有一个固定的字典键
X
,我想用这个键
X
作为
finalResult
创建一个
列表,其中我有一些外部源的
数据

在下面的代码中,我遇到了一个错误,
已经添加了一个具有相同密钥的项。键: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
                }
            });
        }
常量字符串dictKey=“X”; var finalResult=新字典(); var data=新字典{{“A1!D1”,10},{“A2!D2”,20}; foreach(数据中的var(键、值) { 最终结果。添加(dictKey,新列表 { 新生 { Name=key.Split(“!”)[0], Section=key.Split(“!”)[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
    });
}
常量字符串dictKey=“X”; var finalResult=新字典(); var data=新字典{{“A1!D1”,10},{“A2!D2”,20}; foreach(数据中的var(键、值) { //检查字典中是否存在键,如果存在,则返回分配给它的列表 如果(!finalResult.TryGetValue(dictKey,out var list)) { //如果键不存在,我们将为变量“List”分配一个新列表 列表=新列表(); //我们将它添加到字典中,现在当我们调用TryGetValue(dictKey)时,它将返回true,结果值将是我们分配给“List”的列表。 最终结果添加(dictKey,list); } //将该学生添加到列表中。 添加(新学生) { Name=key.Split(“!”)[0], Section=key.Split(“!”)[1], 年龄=价值 }); }
您可以通过以下两种方式之一执行此操作

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

    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=newdictionary{{“A1!D1”,10},{“A2!D2”,20};
    列出所有学生=数据。选择(x=>newstudent()
    {
    Name=x.Key.Split(“!”)[0],
    Section=x.Key.Split(“!”)[1],
    年龄=x.价值
    }).ToList();//需要从IEnumerable转换为List。
    最终结果。添加(dictKey,所有学生);
    
    使用相同的键添加/更新字典

    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.
    }
    
    var data=newdictionary{{“A1!D1”,10},{“A2!D2”,20};
    foreach(数据中的var(键、值)
    {
    //首先创建学生对象,否则重复代码两次。
    学生=新生
    {
    Name=key.Split(“!”)[0],
    Section=key.Split(“!”)[1],
    年龄=价值
    };
    如果(!finalResult.ContainsKey(dictKey))
    Add(dictKey,新列表{student});//新列表
    其他的
    finalResult[dictKey].Add(student);//将新项添加到现有列表中。
    }
    
    那么您希望字典中有一个元素,其键设置为“X”,值设置为学生列表

    var学生=数据
    .选择(d=>new Student
    {
    Name=d.Key.Split(“!”)[0],
    Section=d.Key.Split(“!”)[1],
    年龄=d.值
    })
    .ToList();
    最终结果。添加(听写键,学生);
    
    这是否回答了您的问题?我可以检查键是否存在,但在这两种情况下如何在列表中添加项?这是否回答了您的问题?另外,您必须硬编码
    dictKey
    ,因此它将只具有
    X
    值-字典键必须是唯一的。请澄清您的字典键必须来自何处