本文介绍了如何实现List.Remove针对两个不同的对象列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表:ListA<A>ListB<B>

对象的结构:
对象A:-commonID​​,AName
对象B:-commonID​​,BName

Structure of object:
Object A : - commonID , AName
Object B : - commonID , BName

现在我的目标非常简单,我试图删除ListA中与ListB具有相同commonID的所有项目.以下是我尝试过的方法:

Now my objective is very simple, I'm trying to remove all items in ListA that having the same commonID as in ListB. Below is what I've tried:

foreach(var item in ListB)
    ListA.Remove(x=>x.commonID == item.commonID)

抛出异常:

Cannot convert lambda expression to type 'A' because it is not a delegate type

我可以知道我做错了什么吗?

May I know which part am I doing it wrong?

推荐答案

您当前正在使用 Remove (需要删除单个项目),而不是 RemoveAll (带有谓词).

You're currently using Remove (which takes an individual item to remove) instead of RemoveAll (which takes a predicate).

但是,更好的方法可能是创建要删除的所有ID的集合,然后使用一次对RemoveAll的调用:

However, a better approach might be to create a set of all IDs you want to remove, and then use a single call to RemoveAll:

HashSet<string> idsToRemove = new HashSet<string>(ListB.Select(x => x.commonID));
ListA.RemoveAll(x => idsToRemove.Contains(x.commonID));

或者如果您的列表足够小而不必担心它是O(N * M)操作,则可以使用:

Or if your lists are small enough that you're not worried about it being an O(N*M) operation, you can use:

ListA.RemoveAll(x => ListB.Any(y => x.commonID == y.commonID));

这篇关于如何实现List.Remove针对两个不同的对象列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 22:43