arrays - 从数组中查找对象匹配

标签 arrays c#-4.0

假设我有 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/

相关文章:

c++ - 编译错误声明我的 char vector 数组

c++ - 将参数传递给 "array-like"容器构造函数

c# - 使用数据注释和代码优先的自定义验证属性

c# - 插入数据库按钮代码不起作用不确定如何修复它

c# - 用于 MS 图表控件的鼠标滚轮滚动事件

javascript - 将对象数组推送到数组进行排序

c - 更新函数中的字符串数组 - C

javascript - 从数组指令中删除重复项

JavaScript/Html Pl/sql 验证器。

.net - 创建具有超时的任务