C#List< object> .RemoveAll() - 如何删除列表的子集? [英] C# List<object>.RemoveAll() - How to remove a subset of the list?
问题描述
我有2个类别 feeds_Auto 和产品,具有多个匹配属性。对于这个特殊的问题,AutoID是唯一需要使用的字段。
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.
我有一个列表< FeedsAuto>
和几百个我有一个小的列表<产品>
与10,20个独特的条目。我现在要从大列表中删除小列表中的所有项目。
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.
如何使用RemoveAll({lambda expression})来完成此操作?我发现的所有例子取决于通用列表是简单类型(字符串,整数,等)。
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(????);
}
}
}
是不难的:
foreach (var drop in dropSourceList)
{
source.RemoveAll(a => a.AutoID == drop.AutoID);
}
推荐答案
您可以使用 Any
以简化
source.RemoveAll(a => dropSourceList.Any(b => a.AutoID == b.AutoID));
您可以通过创建 HashSet
ID of first:
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));
这篇关于C#List< object> .RemoveAll() - 如何删除列表的子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!