比较列表A和B的元素并找到列表B中不存在的元素?

时间:2014-03-09 07:48:39

标签: c# .net list loops

我有两个列表

List<int> A= new List<int>()
{33,50,30,90,1,4,5,6,66,
}; 
and 
List<int> B=new List<int>()
   {50,4,33};

现在我想查找列表A中列表B中不存在的所有元素

2 个答案:

答案 0 :(得分:4)

List<int> res = A.Except(B).ToList();

答案 1 :(得分:0)

using System.IO;

using System;

using System.Linq;

using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> A= new List<int>(){33,50,30,90,1,4,5,6,66,}; 
        List<int> B=new List<int>(){50,4,33};

        Console.WriteLine("using linq:");

        foreach(int i in A.Except(B).ToList())
        Console.WriteLine(i);

        Console.WriteLine("without using linq:");

        foreach(int i in Except(A,B))
        Console.WriteLine(i);
    }

    private static List<int> Except(List<int> A,List<int>B)
    {
        List<int> c = new List<int>();
        foreach(int i in A)
        {
            if(B.Contains(i))
               continue;
            else
               c.Add(i);
        }
        return c;
    }

}