Hossain Ehsani
Hossain Ehsani

Reputation: 395

adding new values to dictionary with a list as its value

i have a dictionary like this :

Dictionary<string,List<string>> StudentsByTeacherName = new Dictionary<string,List<string>>();

this dictionary is inside a loop i want the dictionary Value for a specific key get updated in each loop. if there are no new keys there to add to the dictionary

foreach (var item5 in StudentsByTeacherName)
                {
                    if (StudentsByTeacherName.ContainsKey(item5.Key))
                    {

                    }
                    else
                    {
                        StudentsByTeacherName.Add(item4.Value,StudentName);
                    }

                }

Upvotes: 0

Views: 80

Answers (3)

Brody
Brody

Reputation: 2074

Try this.

foreach (var item5 in StudentsByTeacherName)
{
    if(item5.Value == null)
    {
        item5.Value = new List<String();
    }

    item5.Value[item4.Key] = item4.Value;
}

I am assuming that item4 is the Student. This will replace an existing value or add a new value.

Upvotes: 0

Willy David Jr
Willy David Jr

Reputation: 9131

You cannot change your property or indexer value since this is read only. What you can do is access it via its index:

 foreach (var item5 in StudentsByTeacherName)
    {
      if (StudentsByTeacherName.ContainsKey(item5.Key))
         {
            //This will add new values on your list of string on specific 
            //keys and will not delete the existing ones:

            List<string> list = StudentsByTeacherName[item5.Key];
            list.Add("Your additional value here");
         }
         else
         {
            StudentsByTeacherName.Add(item4.Value,StudentName);
         }
    }

This will update the value of string list and not the key itself.

Upvotes: 1

Habib
Habib

Reputation: 223187

i want the dictionary Value for a specific key get updated in each loop. if there are no new keys there to add to the dictionary

For that instead of checking for ContainsKey simply do:

TeacherName[item3.Key] = yourStringList;

The indexer [] will update the existing Key and inserts if the key doesn't exists.

Upvotes: 2

Related Questions