Reputation: 13955
This question is very similar to this one: Use LINQ to get items in one List<>, that are not in another List<>. But the differences are just enough that I'm having trouble nailing down the LINQ syntax.
I have two lists:
List<Fubar> fewBarNew
List<string> existingProviderIDs
Where Fubar
looks like:
Class Fubar
{
int FunbarId int {get; set;}
....
....
string ProviderID {get; set;}
}
Now, I want to remove from fewBarNew
any instance where FewBarNew.ProviderID
exists inside existingProviderIDs
.
fewBarNew = fewBarNew.Where(f => !existingProviderIdList.Any(ep => ?????).ToList();
Upvotes: 0
Views: 522
Reputation: 37299
Any enables you to check if any item in a collections matches some predicate. So you could define the predicate to be "if any item matches the current":
fewBarNew.Where(f => !existingProviderIdList.Any(ep => ep == f.ProviderID));
However, I think a cleaner way will be to use .Contains
:
var result = fewBarNew.Where(f => !existingProviderIDs.Contains(f.ProviderID));
Then, as this performs in O(n^2)
you can improve using a HashSet<string>
instead:
var existingProviderIDSet = new HashSet<string>(existingProviderIDs);
var result = fewBarNew.Where(f => !existingProviderIDSet.Contains(f.ProviderID));
As HashSet
's Contains
performs an O(1)
operation, this will execute in O(n)
.
Upvotes: 6