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)
You can simply check to see that the set difference between query2 and query1 is the empty set: var isSubset = ! query2. Except(query1).
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.
To check if an element is present in the list, use List. Contains() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With