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

查看:365
本文介绍了与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&LT ; IEnumerable的&LT; SomeClass的&GT;&GT;

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>>

感谢所有伟大的答案。原来,有四个选项来解决这样的:列表+聚合(@Marcel戈塞尔林),列表+的foreach (@JaredPar,@Gabe Moothart),的HashSet +聚合(@jesperll)和的HashSet +的foreach (@Tony的小马)。我做了这些解决方案的一些性能测试(不同的列表的数量 若干要素每个列表和随机数最多的大小。

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的性能比列表更好(因为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天全站免登陆