-1

有什么方法可以比较 Dict = Dictionary<string, int>和 Dict_Aggregate=Dictionary<string, string>使用 c#。请注意,这两个字典都生成相同的输出。请建议。目前我正在这样做:

bool dictionariesEqual = Dict.Keys.Count == Dict_Aggregate.Keys.Count && Dict.Keys.All(k => Dict_Aggregate.ContainsKey(k) && object.Equals(Dict_Aggregate[k], Dict[k]));

请建议。

4

1 回答 1

1

您可能想要进行更广泛的比较,这取决于您是否关心这些值是否相同。

这个

bool dictionariesEqual = Dict.Keys.Count == Dict_Aggregate.Keys.Count 
    && Dict.Keys.All(k => Dict_Aggregate.ContainsKey(k);

将确定密钥匹配;如果要匹配值,则必须添加另一个子句并确定如何比较ints 和strings,例如:

bool dictionariesEqual = Dict.Keys.Count == Dict_Aggregate.Keys.Count 
    && Dict.Keys.All(k => Dict_Aggregate.ContainsKey(k) 
    && Dict_Aggregate.All(v => 
      { int test; 
        return int.TryParse(v.Value, out test) 
          && Dict[v.Key].Equals(test); });

显然,最后一个值比较存在一些边缘情况 - 它取决于string值是确切的数字,并且没有空格等。但是,如果需要,您可以对其进行改进。

于 2013-09-13T15:07:27.300 回答