42

I have two lists and I need to compare them and only return a List of Items not in both.

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"} }; 

In this example new Person {Id = 3, Name = "Person 3"} would be the result. A Linq solution would be preferred.

4 Answers 4

45

not in will work for you

var listOfIds = new List<int> {1,2,4}; var query = from item in persons where !listOfIds .Contains( item.id ) select item; 

You can check for more detail : SQL to LINQ ( Case 7 - Filter data by using IN and NOT IN clause)

Sign up to request clarification or add additional context in comments.

2 Comments

Great Thanks, always forget how to do it :-)
There's a function for this, Except, which is not only cleaner, it's also faster.
41

You can also use lambda:

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

Comments

31
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 

Comments

1

With Linq in C# you can do the following variants which give the same results:

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.