Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过lambda从另一个集合中排除集合_C#_List_Lambda - Fatal编程技术网

C# 通过lambda从另一个集合中排除集合

C# 通过lambda从另一个集合中排除集合,c#,list,lambda,C#,List,Lambda,这是我喜欢的类型: public class myType { public int Id { get; set; } public string name { get; set; } } 这种类型的集合有2个: List<myType> FristList= //fill ; List<myType> Excludelist= //fill; 您对上述查询的确切lambda表达式有何建议?三个选项。一个没有任何变化: var excludeI

这是我喜欢的类型:

public class myType
 {
     public int Id { get; set; }
     public string name { get; set; }
 }
这种类型的集合有2个:

List<myType> FristList= //fill ;
List<myType> Excludelist= //fill;

您对上述查询的确切lambda表达式有何建议?

三个选项。一个没有任何变化:

var excludeIds = new HashSet<int>(excludeList.Select(x => x.Id));
var targetList = firstList.Where(x => !excludeIds.Contains(x.Id)).ToList();
或者编写一个通过ID进行比较的
IEqualityComparer
,并使用:

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

在我看来,第二个和第三个选项肯定更好,特别是当你需要在不同的地方做这类工作时。

我同意后一个选项的可能副本更干净,但第一个选项在
excludeList
有大量项目的情况下不会表现更好吗?@richardtallent:no,因为
Except
无论如何都会在内部构建哈希集。
var targetList = firstList.Except(excludeList).ToList();
var targetList = firstList.Except(excludeList, comparer).ToList();