Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use LINQ to get items in one List<>, that are not in another List<>

Tags:

c#

linq

.net-3.5

I would assume there's a simple LINQ query to do this, I'm just not exactly sure how.

Given this piece of code:

class Program {     static void Main(string[] args)     {         List<Person> peopleList1 = new List<Person>();         peopleList1.Add(new Person() { ID = 1 });         peopleList1.Add(new Person() { ID = 2 });         peopleList1.Add(new Person() { ID = 3 });          List<Person> peopleList2 = new List<Person>();         peopleList2.Add(new Person() { ID = 1 });         peopleList2.Add(new Person() { ID = 2 });         peopleList2.Add(new Person() { ID = 3 });         peopleList2.Add(new Person() { ID = 4 });         peopleList2.Add(new Person() { ID = 5 });     } }  class Person {     public int ID { get; set; } } 

I would like to perform a LINQ query to give me all of the people in peopleList2 that are not in peopleList1.

This example should give me two people (ID = 4 & ID = 5)

like image 680
JSprang Avatar asked Oct 15 '10 18:10

JSprang


People also ask

How do you check if a list is a subset of another list C#?

You can simply check to see that the set difference between query2 and query1 is the empty set: var isSubset = ! query2. Except(query1).

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

How do you check if a list contains an object C#?

To check if an element is present in the list, use List. Contains() method.


Video Answer


1 Answers

This can be addressed using the following LINQ expression:

var result = peopleList2.Where(p => !peopleList1.Any(p2 => p2.ID == p.ID)); 

An alternate way of expressing this via LINQ, which some developers find more readable:

var result = peopleList2.Where(p => peopleList1.All(p2 => p2.ID != p.ID)); 

Warning: As noted in the comments, these approaches mandate an O(n*m) operation. That may be fine, but could introduce performance issues, and especially if the data set is quite large. If this doesn't satisfy your performance requirements, you may need to evaluate other options. Since the stated requirement is for a solution in LINQ, however, those options aren't explored here. As always, evaluate any approach against the performance requirements your project might have.

like image 116
Klaus Byskov Pedersen Avatar answered Sep 26 '22 00:09

Klaus Byskov Pedersen