如何将项目添加到包含词典的词典中

本文关键字:包含词 项目 添加 | 更新日期: 2023-09-27 17:56:44

我想将项目添加到包含字典的字典中,请参阅下面的代码。

Dictionary<string, Dictionary<string, int>> dict = new Dictionary<string, Dictionary<string, int>>();
foreach (var item in TrainingCourseList)
{
    // I have to add item.ID,item.Name,item.Score something like below
    dict.Add(item.ID,item.Name,item.Score);
}

如何将项目添加到包含词典的词典中

我想Tuple<string, string, int>最适合您的情况,而不是字典:

var list = TrainingCourseList
    .Select(item => Tuple.Create(item.ID, item.Name, item.Score));

如果你想在外部字典中添加一个条目,你必须做一些类似的事情

Dictionary<string, Dictionary<string, int>> dict = new Dictionary<string, Dictionary<string, int>>();
    foreach (var item in TrainingCourseList)
    {
        // i have to add item.ID,item.Name,item.Score something like below
        dict.Add(item.ID,new Dictionary<string,int>{{item.Name,item.Score}};
    }

尝试

Dictionary<string, Dictionary<string, int>> dict = new Dictionary<string, Dictionary<string, int>>();
foreach (var item in TrainingCourseList)
{
    // i have to add item.ID,item.Name,item.Score something like below
    dict.Add(item.ID, new Dictionary<string, int> { item.Name, item.Score });
}