Use LINQ to get items in one List<>, that are not in another List<>
I would assume there's a simple LINQ query to do this, I'm just not exactly sure how. Please see code snippet below.
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)
var result = peopleList2.Where(p => !peopleList1.Any(p2 => p2.ID == p.ID));
If you override the equality of People then you can also use:
peopleList2.Except(peopleList1)
Except
should be significantly faster than the Where(...Any)
variant since it can put the second list into a hashtable. Where(...Any)
has a runtime of O(peopleList1.Count * peopleList2.Count)
whereas variants based on HashSet<T>
(almost) have a runtime of O(peopleList1.Count + peopleList2.Count)
.
Except
implicitly removes duplicates. That shouldn't affect your case, but might be an issue for similar cases.
Or if you want fast code but don't want to override the equality:
var excludedIDs = new HashSet<int>(peopleList1.Select(p => p.ID));
var result = peopleList2.Where(p => !excludedIDs.Contains(p.ID));
This variant does not remove duplicates.
Or if you want it without negation:
var result = peopleList2.Where(p => peopleList1.All(p2 => p2.ID != p.ID));
Basically it says get all from peopleList2 where all ids in peopleList1 are different from id in peoplesList2.
Just a little bit different approach from the accepted answer :)
链接地址: http://www.djcxy.com/p/51370.html上一篇: 从状态对象导航(1