使用LINQ获取两个列表之间的差异

时间:2011-09-08 11:33:03

标签: c# .net linq list

我有两个列表,我需要比较它们,只返回不在两者中的项目列表。

var listOfIds = new List<int> {1,2,4};

var persons = new ObservableCollection<Person>
{
    new Person {Id = 1, Name = "Person 1"},
    new Person {Id = 2, Name = "Person 2"},
    new Person {Id = 3, Name = "Person 3"},
    new Person {Id = 4, Name = "Person 4"}
};

在此示例中,new Person {Id = 3, Name = "Person 3"}将是结果。 Linq解决方案将是首选。

4 个答案:

答案 0 :(得分:38)

不适合你

var listOfIds = new List<int> {1,2,4};

var query = from item in persons 
            where !listOfIds .Contains( item.id )
            select item;

您可以查看更多详情:SQL to LINQ ( Case 7 - Filter data by using IN and NOT IN clause)

答案 1 :(得分:33)

您也可以使用lambda:

var query = persons.Where(item => !listOfIds.Contains(item.Id));

答案 2 :(得分:1)

var list1 = new List<int> {1,2,3,4,5};
var list2 = new List<int> {2,3,4,5,6};

list1.Except(list2); //1 - items removed
list2.Except(list1); //6 - items added

答案 3 :(得分:0)

使用C#中的Linq,您可以执行以下变体,得到相同的结果:

int[] numbers1 = { 1,2,3,4 };
int[] numbers2 = { 3,4,5,6 };

// Ac V Bc, thus complement of A plus the complement of B
IEnumerable<int> differencesVariant1 = 
numbers1.Except(numbers2).Union(numbers2.Except(numbers1));

// (A V b)c, thus complement of (set A plus set B)
IEnumerable<int> differencesVariant2 = 
numbers1.Union(numbers2).Except(numbers1.Intersect(numbers2));

Console.WriteLine("variant 1:");
foreach (int number in differencesVariant1)
    Console.WriteLine(number);   // prints: 1,2,5,6

Console.WriteLine("variant 2:");
foreach (int number in differencesVariant2)
    Console.WriteLine(number);   // prints: 1,2,5,6