将项目添加到字典中的现有列表

Man*_*yak 1 c# linq

我有一本字典如下

var dicAclWithCommonDsEffectivity = new Dictionary<string, List<int>>();
Run Code Online (Sandbox Code Playgroud)

我有一个如下列表

var dsList=new List<int>();
Run Code Online (Sandbox Code Playgroud)

对于中的每个项目,dsList我将在dicAclWithCommonDsEffectivity字典中搜索列表中的匹配值。如果我找到匹配项,我将获取其密钥并组合所有密钥形成一个新密钥。我将创建一个新列表并添加项目。

foreach (int i in dsList)
{
    var aclWithmatchingDS = dicAclWithCommonDsEffectivity.Where(x => x.Value.Contains(i)).Select(x=>x.Key);
    if (aclWithmatchingDS.Count() > 0)
    {
        string NewKey= aclWithmatchingDS.key1+","aclWithmatchingDS.key2 ;

        //if NewKey is not there in dictionary 
        var lst=new List<int>(){i};
        //Add item to dictionary
        //else if item is present append item to list
        //oldkey,{oldlistItem,i};

    }
}
Run Code Online (Sandbox Code Playgroud)

对于 dsList 中的下一个项目,如果有匹配的键,那么我必须将该项目添加到新字典内的列表中。

如何在不创建新列表的情况下将新项目添加到字典中的列表中。

Paw*_*cki 6

你可能想要这样的东西:

if (dicAclWithCommonDsEffectivity.ContainsKey(NewKey))
{
    dicAclWithCommonDsEffectivity[NewKey].Add(i)
}
else
{
    dicAclWithCommonDsEffectivity.Add(NewKey, lst); // or simply do new List<int>(){ i } instead of creating lst earlier 
}
Run Code Online (Sandbox Code Playgroud)