patterncsharpCritical
Use LINQ to get items in one List<>, that are not in another List<>
Viewed 0 times
linqareuselistnotitemsthatoneanotherget
Problem
I would assume there's a simple LINQ query to do this, I'm just not exactly sure how.
Given this piece of code:
I would like to perform a LINQ query to give me all of the people in
This example should give me two people (ID = 4 & ID = 5)
Given this piece of code:
class Program
{
static void Main(string[] args)
{
List peopleList1 = new List();
peopleList1.Add(new Person() { ID = 1 });
peopleList1.Add(new Person() { ID = 2 });
peopleList1.Add(new Person() { ID = 3 });
List peopleList2 = new List();
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)
Solution
This can be addressed using the following LINQ expression:
An alternate way of expressing this via LINQ, which some developers find more readable:
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.
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.
Context
Stack Overflow Q#3944803, score: 1253
Revisions (0)
No revisions yet.