Search code examples
c#.netlistdictionarykeyvaluepair

How to change value of KeyValuePair in a List as a value in a Dictionary?


I have quite complicated case. I want to change the value of the KeyVluePair in this Dictionary -> Dictionary<string, List<KeyValuePair<string, int>>>

So far I've done this but I don't know how to continue:

string input = Console.ReadLine();
Dictionary<string, List<KeyValuePair<string, int>>> dworfs = new Dictionary<string, List<KeyValuePair<string, int>>>();
while (input != "Once upon a time")
{
   string[] elements = input.Split(new[] { " <:> " }, StringSplitOptions.RemoveEmptyEntries);
   if (dworfs.ContainsKey(elements[0]))
   {
      if (dworfs[elements[0]].Any(x => x.Key.Contains(elements[1])))
      {
         var dworf = dworfs[elements[0]].FirstOrDefault(x => x.Key == elements[1]);
         if (dworf.Value < int.Parse(elements[2]))
         {
            dworfs[elements[0]].FirstOrDefault(x => x.Key == elements[1]) = new KeyValuePair<string,int> (elements[1], int.Parse(elements[2]));
         }
      }
      else
      {
         dworfs[elements[0]].Add(new KeyValuePair<string, int>(elements[1], int.Parse(elements[2])));
      }
   }
   else
   {
      dworfs.Add(elements[0], new List<KeyValuePair<string, int>> { new KeyValuePair<string, int> (elements[1], int.Parse(elements[2])) });
   }
   input = Console.ReadLine();
}

This line dworfs[elements[0]].FirstOrDefault(x => x.Key == elements[1]) = new KeyValuePair<string,int> (elements[1], int.Parse(elements[2])); gives me an error The left hand-side of an assignment must be a variable, property or indexer. I don't know how to assign the value. Can someone help?


Solution

  • The error message describes the issue, the FirstOrDefault() will return with a value which can be only used as the right part of an expression. You can't assign values to method results.

    Try this:

    var index = dworfs[elements[0]].IndexOf(dworf);
    dworfs[elements[0]][index] = new KeyValuePair<string,int> (elements[1], int.Parse(elements[2]));
    

    Keep in mind that FirstOrDefault() could return null but you are not checking for that case in your code, that could lead NullReferenceExceptions.