比较2个词典的最佳方法是什么?其中的项目“应该”始终采用相同的顺序。
dictionary<string, int> _requiredItems = new dictionary<string, int>();
dictionary<string, int> _collectedItems = new dictionary<string, int>();
_requiredItems.Add("Cube", 2); //2 being the number of Cubes required
_collectedItems.Add("Cube", 0); //0 meaning we don't have any collected
_requiredItems.Add("Sphere", 3); //3 being the number of Spheres required
_collectedItems.Add("Sphere", 0); //0 meaning we don't have any collected
//stuff happens here
int _itemCollected = _itemsCollected["Cube"];
_itemsCollected["Cube"] = _itemCollected++;
所以现在可以比较它们。如果_collectedItems values = _requiredItems,则返回true,如果不是false。
答案 0 :(得分:3)
HashSet<KeyValuePair<string, int>>.CreateSetComparer().Compare(
new HashSet<KeyValuePair<string, int>>(dict1),
new HashSet<KeyValuePair<string, int>>(dict1)
);
答案 1 :(得分:1)
您可以使用LINQ All
方法,例如:
var dict1 = new Dictionary<string, int>();
var dict2 = new Dictionary<string, int>();
var result = dict1.All(k => k.Value == dict2[k.Key]);