假设我有 4 个数组:
[1,3,54,4]
[54,2,3,9]
[3,2,9,54]
[54,8,4,3]
我需要获取所有数组中存在的对象(在本例中为整数,但它们将是自定义对象)。在上面的情况下,我需要结果为:[54,3],因为它们是所有四个数组中唯一的两个项目。 顺序并不重要,速度很重要,数组大小和数组数量会有很大差异。 我正在使用 C# 4 和 ASP.NET。数组将是列表,尽管它们可以直接转换。
谢谢:)
最佳答案
怎么样:
ISet<int> intersection = new HashSet<int>(firstArray);
intersection.IntersectWith(secondArray);
intersection.IntersectWith(thirdArray);
intersection.IntersectWith(fourthArray);
请注意,这应该比更明显的更有效:
var x = firstArray.Intersect(secondArray)
.Intersect(thirdArray)
.Intersect(fourthArray);
因为后者将为每个方法调用创建一个新的哈希集。
显然,对于多个数组,您只需循环即可,例如
static ISet<T> IntersectAll<T>(IEnumerable<IEnumerable<T>> collections)
{
using (IEnumerator<T> iterator = collections.GetEnumerator())
{
if (!iterator.MoveNext())
{
return new HashSet<T>();
}
HashSet<T> items = new HashSet<T>(iterator.Current);
while (iterator.MoveNext())
{
items.IntersectWith(iterator.Current);
}
return items;
}
}
关于arrays - 从数组中查找对象匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3405862/