【问题标题】:Remove unmatched records from list从列表中删除不匹配的记录
【发布时间】:2015-08-27 11:33:46
【问题描述】:

我有这样的 ABC 课

public class ABC{
public int Id {get;set;}
public int UserCount {get;set;}
}

现在我将以下记录添加到 ABC 类型的列表中

List<ABC> lstABC = new List<ABC>();
lstABC.Add(new ABC(){Id=1,UserCount=5});
lstABC.Add(new ABC(){Id=2,UserCount=15});
lstABC.Add(new ABC(){Id=3,UserCount=3});
lstABC.Add(new ABC(){Id=4,UserCount=20});
lstABC.Add(new ABC(){Id=5,UserCount=33});
lstABC.Add(new ABC(){Id=6,UserCount=21});

我还有另一个 int 类型的列表

List<int> lstIds = new List<int>();
lstIds.Add(1);
lstIds.Add(3);
lstIds.Add(4);

现在我想在不使用任何循环的情况下从lstABC 中删除其 ID 与lstIds 不匹配的所有项目。最优化的方法是什么?

【问题讨论】:

  • LINQ 是循环的内部语法糖。

标签: linq asp.net-mvc-3 c#-4.0


【解决方案1】:

你可以像这样使用 RemoveAll :

lstABC.RemoveAll(x => !lstIds.Contains(x.Id));

它应该很容易工作

【讨论】:

    【解决方案2】:

    继续@Coder1409 解决方案,使用 HashSet 来提高性能(对于大集合):

    HashSet<int> hashSet = new HashSet<int>(lstIds);
    lstABC.RemoveAll(x => !hashSet.Contains(x.Id));
    

    HTH

    【讨论】:

      【解决方案3】:

      另一种更易于阅读的解决方案

        lstABC = (from l in lstABC
                       where lstIds.Contains(l.Id)
                       select l).ToList();
      

      你也可以只选择匹配的元素而不是删除

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-14
        相关资源
        最近更新 更多