.NET检查是否有两个IEnumerable< T>.具有相同的元素 [英] .NET check if two IEnumerable<T> have the same elements
问题描述
可能重复:
比较两个集合是否相等
Possible Duplicate:
Comparing two collections for equality
我需要验证两个IEnumerable<T>
列表是否具有相同的元素,不一定以相同的顺序.
I need to verify if two IEnumerable<T>
lists have the same elements, not necessarily in the same order.
我的目标是.NET 3.5.
I'm targetting .NET 3.5.
这是测试.问题是,HasSameElements()
应该如何实施?
Here are the tests. The question is, how should HasSameElements()
be implemented?
var l1 = new[]{1,2,3};
var l2 = new[]{3,1,2};
bool rez1 = l1.HasSameElements(l2);//should be true
var l3 = new[]{1,2,3,2};
var l4 = new[]{3,1,2,2};
bool rez2 = l3.HasSameElements(l4);//should be true
var l5 = new[]{1,2,3,2};
var l6 = new[]{1,2,3};
bool rez3 = l5.HasSameElements(l6);//should be false
附加说明:
-
在示例中,我使用的是IEnumerable,但是T可以是任何东西. T是否必须实现
IComparable
?
Enumerable.SequenceEquals()本身不起作用,它期望元素的顺序相同.
Enumerable.SequenceEquals() by itself doesn't work, it expects the same order for the elements.
这是HasElements
的模板:
[只是一些占位符文本作为Markdown'代码格式设置'错误的解决方法]
[just some placeholder text as workaround for Markdown 'code formatting' bug]
public static class Extensions {
public static bool HasElements(this IEnumerable<T> l1, IEnumerable<T> l2){
throw new NotImplementedException();
}
}
推荐答案
只需构建一个字典,将每个对象映射到序列中出现的次数,然后检查所得到的字典是否相等.
Just build a dictionary mapping each object to the number of times it appears in the sequence and then check that the resulting dictionaries are equal.
这里:
static class EnumerableExtensions {
public static bool HasSameElementsAs<T>(
this IEnumerable<T> first,
IEnumerable<T> second
) {
var firstMap = first
.GroupBy(x => x)
.ToDictionary(x => x.Key, x => x.Count());
var secondMap = second
.GroupBy(x => x)
.ToDictionary(x => x.Key, x => x.Count());
return
firstMap.Keys.All(x =>
secondMap.Keys.Contains(x) && firstMap[x] == secondMap[x]
) &&
secondMap.Keys.All(x =>
firstMap.Keys.Contains(x) && secondMap[x] == firstMap[x]
);
}
}
很明显,可以将重复的代码重构为辅助方法,但这只会使这里的想法变得混乱.您可能会幻想并接受GroupBy
用于GroupBy
操作.另外,您应该通过添加null
防护和不添加防护来生产代码.
Obviously the repeated code can be refactored out into helper methods but that would just muddle the idea here. You could get fancy and accept an IEqualityComparer
for the GroupBy
operation. Also, you should productionize the code by adding null
guards and what not.
这篇关于.NET检查是否有两个IEnumerable< T>.具有相同的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!