在LINQ中对一组集合求交集

7

我有一个列表的列表,我想要对它们取交集:

List<List<int>> input = new List<List<int>>();
input.Add(new List<int>() { 1, 2, 4, 5, 8 });
input.Add(new List<int>() { 3, 4, 5 });
input.Add(new List<int>() { 1, 4, 5, 6 });

输出应该是:
{ 4, 5 }

这如何才能简洁地实现?

你需要使用列表吗?为什么不使用哈希集? - Andrew Harry
可能是[使用IEnumerable.Intersect()求多个列表的交集]的重复问题。(https://dev59.com/X3I-5IYBdhLWcg3wxruQ) - Rawling
1个回答

16
var result = input.Cast<IEnumerable<int>>().Aggregate((x, y) => x.Intersect(y))

1
很抱歉第一次出错了,我忘记了我必须要强制转换为IEnumerable<int> - mqp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接