由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(); 

或者,重写EqualsGetHashCode并使用:

 var targetList = firstList.Except(excludeList).ToList(); 

或者编写一个IEqualityComparer ,按ID进行比较,并使用:

 var targetList = firstList.Except(excludeList, comparer).ToList(); 

第二个和第三个选项肯定是更好的IMO,特别是如果你需要在不同的地方做这种工作。