'Add Items To a existing List In a dictionary

I have a dictionary as below

var dicAclWithCommonDsEffectivity = new Dictionary<string, List<int>>();

I have a list as below

var dsList=new List<int>();

For each item in dsList I will search in dicAclWithCommonDsEffectivity dictionary for the matching values in the list. If i find a match I take its Keys and form a new Key combining all the keys. I will create a new list and add item.

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

    }
}

For the next item in dsList if there is a matching key then I have to add the item to the list inside new dictionary.

How to add new item to the list in a dictionary without creating new list.



Solution 1:[1]

You probably want something like that:

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 
}

Solution 2:[2]

I suggest TryGetValue method which is typical in such cases:

List<int> list;

if (dicAclWithCommonDsEffectivity.TryGetValue(NewKey, out list))
  list.Add(i);
else
  dicAclWithCommonDsEffectivity.Add(NewKey, new List<int>() {i});

In case of C# 7.0 you can get rid of list declaration:

if (dicAclWithCommonDsEffectivity.TryGetValue(NewKey, out var list))
  list.Add(i);
else
  dicAclWithCommonDsEffectivity.Add(NewKey, new List<int>() {i});

Solution 3:[3]

Get first KeyValue pair in dicAclWithCommonDsEffectivityand add it to the list, which is the value here and it can be accessed directly:

 if (aclWithmatchingDS.Count() > 0)
 {
   dicAclWithCommonDsEffectivity.Add(NewKey,lst);
 }
 else
 {
    aclWithmatchingDS.First().Value.Add("Here add your item");
 }

Solution 4:[4]

Let me clarify before suggestion, So You want to check for existance of a key in the dictionary, according to some condition, If specific key is present means you want to add the new item to corresponding key or else you want to create a new key and a new list with the new item, if I understand the requirement correctly means you can try the following:

if(dicAclWithCommonDsEffectivity.ConainsKey(NewKey))
{
    aclWithmatchingDS[NewKey].Add(i);
}
else
{
    aclWithmatchingDS.Add(NewKey, new List<int>(){i});
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3
Solution 4