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

时间:2017-09-18 13:29:50

标签: c# unit-testing dictionary ienumerable

以下是我的功能: -

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具有预期的两个值(带有carType“x”),但当我进入foreach循环时,它不会进入并说keyValuePairs的计数为0。然后我尝试获取Count的{​​{1}},keyValuePairs也来了0。我不知道我做错了什么。请帮帮我。

2 个答案:

答案 0 :(得分:3)

keyValuePair.Key是一个KeyValuePair。 你需要:

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

答案 1 :(得分:2)

您正在查看值而不是键。

将您的代码更改为:

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

注意我也在将查询转换为数组。否则循环将失败,因为您修改了集合。