【问题标题】:Remove all entries from collection, which are found in different collection using linq从集合中删除所有条目,这些条目使用 linq 在不同的集合中找到
【发布时间】:2021-04-16 07:53:33
【问题描述】:

假设我们有两个列表:

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

【问题讨论】:

    标签: c# linq collections


    【解决方案1】:

    你可以使用Except:

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

    效率较低的 LINQ 版本:

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

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

    listB.RemoveAll(listA.Contains);
    

    【讨论】:

      【解决方案2】:

      @TimSchmelter 的非 LINQ RemoveAll 可能更高性能的版本使用 HashSet

      var hashA = new HashSet<string>(listA);
      listB.RemoveAll(hashA.Contains);
      

      【讨论】:

        猜你喜欢
        • 2011-05-17
        • 2014-03-08
        • 2020-09-24
        • 2019-10-25
        • 1970-01-01
        • 1970-01-01
        • 2017-10-01
        • 1970-01-01
        相关资源
        最近更新 更多