如何仅比较属于c#中不同键的两个不同字典中的值

时间:2013-08-13 05:44:46

标签: c# dictionary compare key-value-store

我有两个字典作为Dict和Dict_BM。 内容如下: 字典内容: PRODUCT_ID,1113

Dict 2内容: 测试,1113

我只想比较两个字典中的'1113'值,因为'Test'是来自Dict_BM中捕获的其他XML的'Product_ID'的值。

到目前为止,

代码如下:

bool equal = false;
    if (Dict.Count == Dict_BM.Count) 
    {
        equal = true;
        foreach (var pair in Dict)
        {
        int value;
        if (Dict_BM.TryGetValue(pair.Key, out value))
        {
            // Require value be equal.
            if (value != pair.Value)
            {
            equal = false;
            break;
            }
        }
        else
        {
            // Require key be present.
            equal = false;
            break;
        }
        }

2 个答案:

答案 0 :(得分:0)

测试字典是否具有相同的值(但是,可能是不同的键)

public static Boolean DictionaryHaveEqualValues(IDictionary left, IDictionary right) {
  if (Object.ReferenceEquals(left, right))
    return true;
  else if (Object.ReferenceEquals(left, null))
    return false;
  else if (Object.ReferenceEquals(right, null))
    return false;

  if (left.Count != right.Count)
    return false;

  Dictionary<Object, int> reversed = new Dictionary<Object, int>();

  foreach (var value in left.Values)
    if (reversed.ContainsKey(value))
      reversed[value] = reversed[value] + 1;
    else
      reversed.Add(value, 1);

  foreach (var value in right.Values)
    if (!reversed.ContainsKey(value))
      return false;
    else if (reversed[value] == 1)
      reversed.Remove(value);
    else
      reversed[value] = reversed[value] - 1;

  return (reversed.Count == 0);
}

....

Dictionary<int, String> main = new Dictionary<int, String>() {
  {1, "A"},
  {2, "B"},
  {3, "A"}
};

Dictionary<int, String> test1 = new Dictionary<int, String>() {
  {7, "A"},
  {4, "B"},
  {5, "A"}
};

Dictionary<int, String> test2 = new Dictionary<int, String>() {
  {7, "A"},
  {4, "B"},
  {5, "A"},
  {9, "B"}
 };

Dictionary<int, String> test3 = new Dictionary<int, String>() {
  {7, "A"},
  {4, "C"},
  {5, "A"},
};

// Dictionarys have equal values: two "A" and one "B"
Debug.Assert(DictionaryHaveEqualValues(main, test1));

// Unequal: test2 simply has move values
Debug.Assert(!DictionaryHaveEqualValues(main, test2));

// Unequal: test3 doesn't have "B" value
Debug.Assert(!DictionaryHaveEqualValues(main, test3));

答案 1 :(得分:0)

我猜你试图比较两个字典的值,对吧?

这可能就是你想要的:

   var equals = (Dict.Count == Dict_BM.Count) && 
                (!Dict.Values.Except(Dict_BM.Values).Any()) && 
                (!Dict_BM.Values.Except(Dict.Values).Any());