多个列表与 IEnumerable.Intersect() 的交集 [英] Intersection of multiple lists with IEnumerable.Intersect()

查看:23
本文介绍了多个列表与 IEnumerable.Intersect() 的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表,我想像这样找到交集:

I have a list of lists which I want to find the intersection for like this:

var list1 = new List<int>() { 1, 2, 3 };
var list2 = new List<int>() { 2, 3, 4 };
var list3 = new List<int>() { 3, 4, 5 };
var listOfLists = new List<List<int>>() { list1, list2, list3 };

// expected intersection is List<int>() { 3 };

有没有办法用 IEnumerable.Intersect() 做到这一点?

Is there some way to do this with IEnumerable.Intersect()?

我应该更清楚这一点:我真的有一个列表列表,我不知道会有多少,上面的三个列表只是一个例子,我实际上拥有的是一个 IEnumerable>

I should have been more clear on this: I really have a list of lists, I don't know how many there will be, the three lists above was just an example, what I have is actually an IEnumerable<IEnumerable<SomeClass>>

感谢所有精彩的回答.结果证明有四个选项可以解决这个问题:List+aggregate(@Marcel Gosselin)、List+foreach(@JaredPar、@Gabe Moothart)、HashSet+aggregate (@jesperll) 和 HashSet+foreach (@Tony the Pony).我对这些解决方案进行了一些性能测试(不同的列表数量、每个列表中的元素数量最大随机数大小.

Thanks for all great answers. It turned out there were four options for solving this: List+aggregate (@Marcel Gosselin), List+foreach (@JaredPar, @Gabe Moothart), HashSet+aggregate (@jesperll) and HashSet+foreach (@Tony the Pony). I did some performance testing on these solutions (varying number of lists, number of elements in each list and random number max size.

事实证明,在大多数情况下,HashSet 的性能比 List 更好(除了大列表和小随机数,我猜是因为 HashSet 的性质.)我找不到 foreach 方法和聚合方法之间的任何真正区别(foreach 方法执行稍微更好.)

It turns out that for most situations the HashSet performs better than the List (except with large lists and small random number size, because of the nature of HashSet I guess.) I couldn't find any real difference between the foreach method and the aggregate method (the foreach method performs slightly better.)

对我来说,聚合方法真的很吸引人(我将其作为公认的答案)但我不会说这是最易读的解决方案..再次感谢大家!

To me, the aggregate method is really appealing (and I'm going with that as the accepted answer) but I wouldn't say it's the most readable solution.. Thanks again all!

推荐答案

怎么样:

var intersection = listOfLists
    .Skip(1)
    .Aggregate(
        new HashSet<T>(listOfLists.First()),
        (h, e) => { h.IntersectWith(e); return h; }
    );

通过这种方式,它通过始终使用相同的 HashSet 进行优化,并且仍然在单个语句中.只需确保 listOfLists 始终包含至少一个列表.

That way it's optimized by using the same HashSet throughout and still in a single statement. Just make sure that the listOfLists always contains at least one list.

这篇关于多个列表与 IEnumerable.Intersect() 的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆