由lambda排除另一个集合
这是我的类型:
public class myType { public int Id { get; set; } public string name { get; set; } }
这种类型有2个集合:
List FristList= //fill ; List Excludelist= //fill;
我需要从FristList
排除Excludelist
,如下所示:
List targetList = FirstList.Where(m=>m.Id not in (Excludelist.Select(t=>t.Id));
关于上述查询的确切lambda表达式,您有什么建议?
三种选择。 一个没有任何变化:
var excludeIds = new HashSet(excludeList.Select(x => x.Id)); var targetList = firstList.Where(x => !excludeIds.Contains(x.Id)).ToList();
或者,重写Equals
和GetHashCode
并使用:
var targetList = firstList.Except(excludeList).ToList();
或者编写一个IEqualityComparer
,按ID进行比较,并使用:
var targetList = firstList.Except(excludeList, comparer).ToList();
第二个和第三个选项肯定是更好的IMO,特别是如果你需要在不同的地方做这种工作。
上述就是C#学习教程:由lambda排除另一个集合分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1010375.html