在C#linq中查找多个列表中的常用项

Ins*_*Man 0 c# linq

我搜索过,但我发现只有与两个列表相关的答案.但是当它们超过两个时呢?

List 1 = 1,2,3,4,5
List 2 = 6,7,8,9,1
List 3 = 3,6,9,2,0,1
List 4 = 1,2,9,0,5
List 5 = 1,7,8,6,5,4
List 6 = 1
List 7 =
Run Code Online (Sandbox Code Playgroud)

如何获得常见物品?你可以看到其中一个是空的,所以常见的是空的,但我需要跳过空列表.

Ofi*_*ten 5

你可以链Intersect:

List<int> List1 = new List<int> {1, 2, 3, 4, 5};
List<int> List2 = new List<int> { 6, 7, 8, 9, 1 };
List<int> List3 = new List<int> { 3, 6, 9, 2, 0, 1 };
List<int> List4 = new List<int> { 1, 2, 9, 0, 5 };
List<int> List5 = new List<int> { 1, 7, 8, 6, 5, 4 };
List<int> List6 = new List<int> { 1 };

List<int> common = List1
  .Intersect(List2)
  .Intersect(List3)
  .Intersect(List4)
  .Intersect(List5)
  .Intersect(List6)
  .ToList();
Run Code Online (Sandbox Code Playgroud)


Ant*_*sek 5

var data = new List<List<int>> {
    new List<int> {1, 2, 3, 4, 5},
    new List<int> {6, 7, 2, 8, 9, 1},
    new List<int> {3, 6, 9, 2, 0, 1},
    new List<int> {1, 2, 9, 0, 5},
    new List<int> {1, 7, 8, 6, 2, 5, 4},
    new List<int> {1, 7, 2}
};


List<int> res = data
    .Aggregate<IEnumerable<int>>((a, b) => a.Intersect(b))
    .ToList();
Run Code Online (Sandbox Code Playgroud)

明确给出了 Aggregate 的类型,否则两个 List 的聚合也必须是 List。它可以很容易地适应并行运行:

List<int> res = data
    .AsParallel<IEnumerable<int>>()
    .Aggregate((a, b) => a.Intersect(b))
    .ToList();
Run Code Online (Sandbox Code Playgroud)

编辑

除了......它不会并行运行。问题是 IEnumerable 上的操作被推迟,因此即使它们在并行上下文中逻辑合并,实际合并发生在ToList()单线程中。对于并行执行,最好离开 IEnumerable 并返回到列表:

List<int> res = data
    .AsParallel()
    .Aggregate((a, b) => a.Intersect(b).ToList());
Run Code Online (Sandbox Code Playgroud)