c# - LINQ 相交,多个列表,一些为空

标签 c# linq

我正在尝试寻找与 LINQ 的交叉点。

示例:

List<int> int1 = new List<int>() { 1,2 };
List<int> int2 = new List<int>();
List<int> int3 = new List<int>() { 1 };
List<int> int4 = new List<int>() { 1, 2 };
List<int> int5 = new List<int>() { 1 };

想要返回:1,因为它存在于所有列表中。如果我运行:

var intResult= int1
            .Intersect(int2)
            .Intersect(int3)
            .Intersect(int4)
            .Intersect(int5).ToList();

它什么都不返回,因为 1 显然不在 int2 列表中。无论一个列表是否为空,我如何让它工作?

使用上面的例子或者:

List<int> int1 = new List<int>() { 1,2 };
List<int> int2 = new List<int>();
List<int> int3 = new List<int>();
List<int> int4 = new List<int>();
List<int> int5 = new List<int>();

在这种情况下我如何返回 1 和 2。我不知道列表是否已填充...

最佳答案

如果您需要一步完成,最简单的解决方案是过滤掉空列表:

public static IEnumerable<T> IntersectNonEmpty<T>(this IEnumerable<IEnumerable<T>> lists)
{
    var nonEmptyLists = lists.Where(l => l.Any());
    return nonEmptyLists.Aggregate((l1, l2) => l1.Intersect(l2));
}

然后您可以在列表集合或其他 IEnumerable 上使用它:

IEnumerable<int>[] lists = new[] { l1, l2, l3, l4, l5 };
var intersect = lists.IntersectNonEmpty();

您可能更喜欢常规的静态方法:

public static IEnumerable<T> IntersectNonEmpty<T>(params IEnumerable<T>[] lists)
{
    return lists.IntersectNonEmpty();
}

var intersect = ListsExtensionMethods.IntersectNonEmpty(l1, l2, l3, l4, l5);

关于c# - LINQ 相交,多个列表,一些为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3191810/

相关文章:

c# - Linq to XML 通过查询子元素获取父元素属性值

c# - RavenDB 嵌套 LINQ 表达式的解决方法

c# - LINQ-to-SQL 在动态列上搜索?

c# - 缓存 LINQ 查询 - IEnumerable.Skip()

c# - Odbc INSERT 不工作

c# - 如何屏蔽字符串?

c# - 获取所有连接的智能卡的列表

LINQ 语法序列

c# - 如何使用 LINQ 比较两个 IEnumerable 集合

c# - 如何在单元测试中将 Thread.CurrentPrincipal 重置为未验证