I have a 2 classes feeds_Auto and Product with multiple matching properties. For this particular problem, the AutoID is the only field I need to use.
I have a List<FeedsAuto>
with several hundred unique entries. I have a small List<Product>
with 10, 20 unique entries. I now want to remove all items in the small list from the large list.
How do I use RemoveAll({lambda expression}) to accomplish this? All of the examples I have found depend on the generic list being of simple types (strings, ints, etc).
private static int DoInserts(ref List<Model.feeds_Auto> source, ref List<Model.Product> target, Guid companyID)
{
List<Model.Product> newProductList = new List<Model.Product>();
List<Model.Product> dropSourceList = new List<Model.Product>();
using (var db = Helpers.GetProdDB())
{
foreach (var src in source)
{
var tgt = target.Where(a => a.alternateProductID == src.AutoID && a.LastFeedUpdate < src.DateModified).FirstOrDefault();
if (tgt == null)
{
newProductList.Add(new Model.Product{...});
dropSourceList.Add(src);
}
}
db.SaveChanges();
if (dropSourceList.Count > 0)
{
source.RemoveAll(????);
}
}
}
To do this in a loop is not difficult:
foreach (var drop in dropSourceList)
{
source.RemoveAll(a => a.AutoID == drop.AutoID);
}
It just does not make sense (to me) to loop on a set to call RemoveAll for one item in each pass.
You can use Any
to simplify
source.RemoveAll(a => dropSourceList.Any(b => a.AutoID == b.AutoID));
You can reduce the looping by creating a HashSet
of ID's first:
var toRemove = new HashSet<int>(dropSourceList.ConvertAll(a => a.AutoID));
source.RemoveAll(a => toRemove.Contains(a.AutoID));
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