如何在c#中的列表中使用Except方法

Lak*_*hae 24 .net c# ienumerable list

我创建了一个两个int类型列表,并使用except方法将list1中的项目分配给list1.例如

List<int> list1 = new List<int>();
List<int> list2 = new List<int>();

list1 = {1,2,3,4,5,6} // get items from the database
list2 = {3,5,6,7,8}   // get items from the database

list1 = list1.Except(list2); // gives me an error.
Run Code Online (Sandbox Code Playgroud)

请给我一些建议.什么是正确的方法.

Mic*_*uda 59

Except方法返回IEnumerable,您需要将结果转换为list:

list1 = list1.Except(list2).ToList();
Run Code Online (Sandbox Code Playgroud)