Compare two lists to search common items

后端 未结 2 1986
梦如初夏
梦如初夏 2020-12-06 05:01
List one //1, 3, 4, 6, 7
List second //1, 2, 4, 5

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

相关标签:
2条回答
  • 2020-12-06 05:43

    You can use the Intersect method.

    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

    0 讨论(0)
  • 2020-12-06 05:43
    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();
            }
    
    0 讨论(0)
提交回复
热议问题