C# 比较两个列表以搜索常见项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11739986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:01:59  来源:igfitidea点击:

Compare two lists to search common items

c#linqcomparison

提问by Saint

List<int> one //1, 3, 4, 6, 7
List<int> second //1, 2, 4, 5

How to get all elements from one list that are present also in second list?

如何从一个列表中获取也存在于第二个列表中的所有元素?

In this case should be: 1, 4

在这种情况下应该是:1、4

I talk of course about method without foreach. Rather linq query

我当然谈论没有 foreach 的方法。而是 linq 查询

采纳答案by sloth

You can use the Intersectmethod.

您可以使用相交方法。

var result = one.Intersect(second);


Example:

例子:

void Main()
{
    List<int> one = new List<int>() {1, 3, 4, 6, 7};
    List<int> second = new List<int>() {1, 2, 4, 5};

    foreach(int r in one.Intersect(second))
        Console.WriteLine(r);
}

Output:

输出:

1
4

1
4

回答by Dhanasekar

static void Main(string[] args)
        {
            List<int> one = new List<int>() { 1, 3, 4, 6, 7 };
            List<int> second = new List<int>() { 1, 2, 4, 5 };

            var result = one.Intersect(second);

            if (result.Count() > 0)
                result.ToList().ForEach(t => Console.WriteLine(t));
            else
                Console.WriteLine("No elements is common!");

            Console.ReadLine();
        }