这是我的类型:
public class myType
{
public int Id { get; set; }
public string name { get; set; }
}
此类型有2个集合:
List<myType> FristList= //fill ;
List<myType> Excludelist= //fill;
我需要从Excludelist
中排除FristList
,如下所示:
List<myType> targetList =
FirstList.Where(m=>m.Id not in (Excludelist.Select(t=>t.Id));
您对上述查询的确切lambda表达式有何建议?
答案 0 :(得分:14)
三种选择。一个没有任何变化:
var excludeIds = new HashSet<int>(excludeList.Select(x => x.Id));
var targetList = firstList.Where(x => !excludeIds.Contains(x.Id)).ToList();
或者,覆盖Equals
和GetHashCode
并使用:
var targetList = firstList.Except(excludeList).ToList();
或者写一个{ID}来比较ID,并使用:
IEqualityComparer<MyType>
第二和第三种选择肯定是更好的IMO,特别是如果你需要在不同的地方做这种工作。