c# – LINQ相交,多个列表,一些空
发布时间:2020-12-15 06:42:05 所属栏目:百科 来源:网络整理
导读:我试图找到一个与LINQ的交点. 样品: Listint int1 = new Listint() { 1,2 };Listint int2 = new Listint();Listint int3 = new Listint() { 1 };Listint int4 = new Listint() { 1,2 };Listint int5 = new Listint() { 1 }; 想要返回:1,因为它存在于所有列
我试图找到一个与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)); } 然后,您可以将其用于列表或其他IEnumerables的集合: 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,l5); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |