从集合中删除所有条目,这些条目使用linq在不同的集合中找到

c#

假设我们有两个列表:

List<string> listA = new List<string>{"a", "c"};
List<string> listB = new List<string>{"a", "a", "b", "c", "d"};

我们想从 listB 中删除 listA 中的所有重复项。

listA 应该保持不变

listB 应该留下元素 {"b", "d"}

一个明显的解决方案是使用循环进行迭代,但我想知道如何使用 System.Linq one-liner 完成此操作?

也许像...

listB.RemoveAll(x => x.Equals(??));

或者...

listA.ForEach(key => listB.RemoveAll(x => x.Equals(key))); // cannot convert string[] to void

回答

您可以使用Except

listB = listB.Except(listA).ToList();

效率较低的 LINQ 版本:

listB = listB.Where(b => !listA.Contains(b)).ToList();

不需要创建新列表的非 LINQ 版本:

listB.RemoveAll(listA.Contains);


以上是从集合中删除所有条目,这些条目使用linq在不同的集合中找到的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>