使用 linq 从集合中删除所有在不同集合中找到的条目
Remove all entries from collection, which are found in different collection using linq
假设我们有两个列表:
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 单行代码来完成?
也许像...
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);
@TimSchmelter 的非 LINQ RemoveAll
的性能可能更高的版本使用 HashSet
:
var hashA = new HashSet<string>(listA);
listB.RemoveAll(hashA.Contains);
假设我们有两个列表:
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 单行代码来完成?
也许像...
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);
@TimSchmelter 的非 LINQ RemoveAll
的性能可能更高的版本使用 HashSet
:
var hashA = new HashSet<string>(listA);
listB.RemoveAll(hashA.Contains);