0

我有两个字典,分别是 Dict 和 Dict_BM。内容如下: 字典内容:Product_ID,1113

字典 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;
        }
        }
4

2 回答 2

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));
于 2013-08-13T06:02:45.247 回答
0

我猜你是想比较两个字典的值,对吧?

可能这就是你想要的:

   var equals = (Dict.Count == Dict_BM.Count) && 
                (!Dict.Values.Except(Dict_BM.Values).Any()) && 
                (!Dict_BM.Values.Except(Dict.Values).Any());
于 2013-08-13T06:20:53.467 回答