【问题标题】:Compare 2 dictionaries比较 2 个词典
【发布时间】:2013-10-21 00:25:12
【问题描述】:

比较两本词典的最佳方法是什么?其中的项目“应该”始终保持相同的顺序。

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 值 = _requiredItems 值,则返回 true,如果不是 false。

【问题讨论】:

    标签: c# .net linq c#-4.0


    【解决方案1】:
    HashSet<KeyValuePair<string, int>>.CreateSetComparer().Compare(
        new HashSet<KeyValuePair<string, int>>(dict1),
        new HashSet<KeyValuePair<string, int>>(dict1)
    );
    

    【讨论】:

      【解决方案2】:

      您可以使用 LINQ All 方法,例如:

      var dict1 = new Dictionary<string, int>();
      var dict2 = new Dictionary<string, int>();
      
      var result = dict1.All(k => k.Value == dict2[k.Key]);
      

      【讨论】:

      • 如果dict2 缺少键,这将引发异常,如果dict1 缺少键,则会返回误报。
      • @SLaks,它会的。和?看来这不是OP的情况。
      猜你喜欢
      • 2012-02-13
      • 1970-01-01
      • 1970-01-01
      • 2014-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-09
      相关资源
      最近更新 更多