从列表中删除不匹配的记录
Remove unmatched records from list
我有一个 class 像这样的 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
不匹配的所有项目,而不使用任何循环。最优化的方法是什么?
您可以像这样使用 RemoveAll :
lstABC.RemoveAll(x => !lstIds.Contains(x.Id));
它应该很容易工作
继续 @Coder1409 解决方案,使用 HashSet 提高性能(对于大集合):
HashSet<int> hashSet = new HashSet<int>(lstIds);
lstABC.RemoveAll(x => !hashSet.Contains(x.Id));
HTH
另一种更易读的解决方案
lstABC = (from l in lstABC
where lstIds.Contains(l.Id)
select l).ToList();
除了删除之外,您还可以 select 只删除匹配的元素
我有一个 class 像这样的 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
不匹配的所有项目,而不使用任何循环。最优化的方法是什么?
您可以像这样使用 RemoveAll :
lstABC.RemoveAll(x => !lstIds.Contains(x.Id));
它应该很容易工作
继续 @Coder1409 解决方案,使用 HashSet 提高性能(对于大集合):
HashSet<int> hashSet = new HashSet<int>(lstIds);
lstABC.RemoveAll(x => !hashSet.Contains(x.Id));
HTH
另一种更易读的解决方案
lstABC = (from l in lstABC
where lstIds.Contains(l.Id)
select l).ToList();
除了删除之外,您还可以 select 只删除匹配的元素