我想要比较两个Dictionary<string, string>实例的内容,而不管它们包含的项的顺序如何。SequenceEquals还会比较顺序,所以我首先按键对字典进行排序,然后调用SequenceEquals。
有没有方法可以用来代替SequenceEquals,只比较内容?
如果没有,这是不是最理想的方式呢?
Dictionary<string, string> source = new Dictionary<string, string>();
Dictionary<string, string> target = new Dictionary<string, string>();
source["foo"] = "bar";
source["baz"] = "zed";
source["blah"] = null;
target["baz"] = "zed";
target["blah"] = null;
target["foo"] = "bar";
// sequenceEquals will be false
var sequenceEqual = source.SequenceEqual(target);
// contentsEqual will be true
var contentsEqual = source.OrderBy(x => x.Key).SequenceEqual(target.OrderBy(x => x.Key));发布于 2010-10-14 07:24:43
var contentsEqual = source.DictionaryEqual(target);
// ...
public static bool DictionaryEqual<TKey, TValue>(
this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second)
{
return first.DictionaryEqual(second, null);
}
public static bool DictionaryEqual<TKey, TValue>(
this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second,
IEqualityComparer<TValue> valueComparer)
{
if (first == second) return true;
if ((first == null) || (second == null)) return false;
if (first.Count != second.Count) return false;
valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;
foreach (var kvp in first)
{
TValue secondValue;
if (!second.TryGetValue(kvp.Key, out secondValue)) return false;
if (!valueComparer.Equals(kvp.Value, secondValue)) return false;
}
return true;
}发布于 2010-10-14 07:24:49
我不知道是否有现有的方法,但您可以使用以下方法(为简洁起见,省略了对args的null检查)
public static bool DictionaryEquals<TKey,TValue>(
this Dictionary<TKey,TValue> left,
Dictionary<TKey,TValue> right ) {
var comp = EqualityComparer<TValue>.Default;
if ( left.Count != right.Count ) {
return false;
}
foreach ( var pair in left ) {
TValue value;
if ( !right.TryGetValue(pair.Key, out value)
|| !comp.Equals(pair.Value, value) ) {
return false;
}
}
return true;
}最好是添加一个重载以允许自定义EqualityComparer<TValue>。
发布于 2017-01-19 23:03:44
如果您使用SortedDictionary,则不需要自己应用排序,这样使用起来会稍微简单一些:
void Main()
{
var d1 = new Dictionary<string, string>
{
["a"] = "Hi there!",
["b"] = "asd",
["c"] = "def"
};
var d2 = new Dictionary<string, string>
{
["b"] = "asd",
["a"] = "Hi there!",
["c"] = "def"
};
var sortedDictionary1 = new SortedDictionary<string, string>(d1);
var sortedDictionary2 = new SortedDictionary<string, string>(d2);
if (sortedDictionary1.SequenceEqual(sortedDictionary2))
{
Console.WriteLine("Match!");
}
else
{
Console.WriteLine("Not match!");
}
}https://stackoverflow.com/questions/3928822
复制相似问题