代码之家  ›  专栏  ›  技术社区  ›  OldSchool

迭代KeyValuePair(作为字典中的键)不起作用

  •  1
  • OldSchool  · 技术社区  · 7 年前

    public void deleteAllCarsWithType(Dictionary < KeyValuePair<string, string> , car > dictCar, string typeOfCar)
    {
      var keyValuePairs = dictCar.Where(keyValuePair => keyValuePair.Key.Equals(typeOfCar));
    
      //var count = keyValuePairs.Count();
      //this also gives the size of keyValuePairs as 0.
    
      foreach (var keyValuePair in keyValuePairs)
      {
        dictCar.Remove(keyValuePair.Key);
      }
    } 
    

    KeyValuePair<string, string> 哪一个是字典的关键,有 carType carModel 作为汽车的模型。

    当我运行它的单元测试时

    [TestMethod]
    public void DeleteSameCarTypeTest()
    {
      Dictionary<KeyValuePair<string, string>, car> Dictionary = new Dictionary<KeyValuePair<string, string>, car>();
      Dictionary.Add(new KeyValuePair<string, string>("x", "y"), new car());
      Dictionary.Add(new KeyValuePair<string, string>("x", "z"), new car());
    
      new Program().deleteAllCarsWithType(Dictionary, "x");
      Assert.AreEqual(0, Dictionary.Count);
    }
    

    它失败了,说预期 0 2 .

    当我调试它时,我发现 keyValuePairs 具有预期的两个值(与 车辆类型 键值对 0 Count 也即将到来 . 我不知道我做错了什么。请帮帮我。

    2 回复  |  直到 7 年前
        1
  •  3
  •   Yair Halberstadt    7 年前

    您需要:

    var keyValuePairs = dictCar.Where(keyValuePair => keyValuePair.Key.Key.Equals(typeOfCar));
    

    private static void deleteAllCarsWithType(Dictionary<KeyValuePair<string, string>, car> dictCar, string typeOfCar)
    {
        var keyValuePairs = dictCar.Where(keyValuePair => keyValuePair.Key.Key.Equals(typeOfCar)).ToArray();
    
        foreach (var keyValuePair in keyValuePairs)
        {
            dictCar.Remove(keyValuePair.Key);
        }               
    }
    
        2
  •  2
  •   JuanR    7 年前

    您正在查看与键相反的值。

    将代码更改为:

    private static void deleteAllCarsWithType(Dictionary<KeyValuePair<string, string>, car> dictCar, string typeOfCar)
    {
        var keyValuePairs = dictCar.Keys.Where(keyValuePair => keyValuePair.Key.Equals(typeOfCar)).ToArray();
    
        foreach (var keyValuePair in keyValuePairs)
        {
            dictCar.Remove(keyValuePair);
        }               
    }
    

    注意,我还将查询转换为数组。否则,由于修改了集合,循环将失败。