C # List <object> .RemoveAll () - How to remove a subset of a list?

I have 2 classes feeds_Auto and a Product with several suitable properties. For this particular problem, 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. Now I want to remove all items from a small list from a large list.

How to use RemoveAll ({lambda expression}) for this? All the examples I found depend on a general list of simple types (strings, int, 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(????); } } } 

It is not difficult to do this in a loop:

 foreach (var drop in dropSourceList) { source.RemoveAll(a => a.AutoID == drop.AutoID); } 

I just have nothing to do to loop on the set to call RemoveAll for one element in each pass.

+6
source share
1 answer

You can use Any to simplify

 source.RemoveAll(a => dropSourceList.Any(b => a.AutoID == b.AutoID)); 

You can reduce the loop by first creating a HashSet identifier:

 var toRemove = new HashSet<int>(dropSourceList.ConvertAll(a => a.AutoID)); source.RemoveAll(a => toRemove.Contains(a.AutoID)); 
+13
source

Source: https://habr.com/ru/post/891846/


All Articles