【问题标题】:How to change value of KeyValuePair in a List as a value in a Dictionary?如何将列表中 KeyValuePair 的值更改为字典中的值?
【发布时间】:2019-03-29 22:33:11
【问题描述】:

我的案子很复杂。我想更改此字典中 KeyVluePair 的值 -> Dictionary<string, List<KeyValuePair<string, int>>>

到目前为止我已经完成了,但我不知道如何继续:

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

dworfs[elements[0]].FirstOrDefault(x =&gt; x.Key == elements[1]) = new KeyValuePair&lt;string,int&gt; (elements[1], int.Parse(elements[2])); 这一行给了我一个错误赋值的左侧必须是变量、属性或索引器。我不知道如何分配价值。有人可以帮忙吗?

【问题讨论】:

    标签: c# .net list dictionary keyvaluepair


    【解决方案1】:

    如果KeyValuePairDictionary,您将有更多机会。

    然而

    var dwarf = dworfs[elements[0]];
    var obj = dwarf.FirstOrDefault(x => x.Key == elements[1]);
    var index = dwarf.IndexOf(obj);
    
    dwarf[index] = new KeyValuePair<string, int>(elements[1], int.Parse(elements[2]));
    

    提示您不需要在一行中完成所有操作

    【讨论】:

    • 其实你的台词有误。应该是var object = dwarf.FirstOrDefault(x =&gt; x.Key == elements[1]); 谢谢。它帮助了我。
    【解决方案2】:

    错误消息描述了该问题,FirstOrDefault() 将返回一个值,该值只能用作表达式的右侧部分。您不能为方法结果赋值。

    试试这个:

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

    请记住,FirstOrDefault() 可能返回 null,但您没有在代码中检查这种情况,这可能导致 NullReferenceExceptions。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      相关资源
      最近更新 更多