C#查找两个或多个列表共有的数字 [英] C# find a number common to two or more lists

查看:258
本文介绍了C#查找两个或多个列表共有的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查找两个或两个以上List中都存在的数字列表的语法是什么?当我只需要检查两个列表时,我一直在循环浏览,但是现在我需要做几个...

What is the syntax for finding a list of numbers both present in two or more List? I was looping through when I only needed to check two lists, but now I need to do several... Something like

List<int> commonIds = SELECT id from list1 
                     where list1.contains(id), 
                           list2.contains(id), 
                           list3.contains(id) ... 

推荐答案

查找任意数量的列表的交集

如果要查找列表的 all 中存在的一组数字,则Enumerable.Intersect是这样做的一个好方法.您甚至不必对列表集合进行硬编码,它可以在运行时创建:

Finding the intersection of any number of lists

If you want to find the set of numbers that exist in all of the lists then Enumerable.Intersect is a good way to do so. You don't even have to hardcode the collection of lists, it can be created at runtime:

var lists = new[] { list1, list2, ..., listN }; // dynamically specified

var common = lists.First().AsEnumerable();
foreach (var list in lists.Skip(1))
{
    common = common.Intersect(list);
}

// and now common has the result, e.g.
var listOfCommonEntries = common.ToList();

查找主列表与彼此之间的交集并

如果要查找包含列表1和列表2之间的所有公共数字的集合,则将列表1和列表N之间的所有公共数字合并,则有些不同:

Finding the union of intersections between master list and each other one

If you want to find the set which includes all common numbers between list 1 and list 2, union all common numbers between list 1 and list N, then it's somewhat different:

var common = Enumerable.Empty<int>();
foreach (var list in lists.Skip(1))
{
    common = common.Union(lists.First().Intersect(list));
}

这篇关于C#查找两个或多个列表共有的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆