LINQ除运算符位于LINQ中的“设置运算符”类别下
该Except()
方法需要两个集合,并找到第二个集合中不存在的那些元素
除了扩展方法不会为复杂类型的集合返回正确的结果。
Except()
方法例using System; using System.Collections.Generic; using System.Linq; namespace DemoApplication { class Program { static void Main(string[] args) { List<string> animalsList1 = new List<string> { "tiger", "lion", "dog" }; Console.WriteLine($"List1中的值:"); foreach (var val in animalsList1) { Console.WriteLine($"{val}"); } List<string> animalsList2 = new List<string> { "tiger", "cat", "deer" }; Console.WriteLine($"List2中的值:"); foreach (var val in animalsList1) { Console.WriteLine($"{val}"); } var animalsList3 = animalsList1.Except(animalsList2); Console.WriteLine($"不在List2中的List1中的值:"); foreach (var val in animalsList3) { Console.WriteLine($"{val}"); } Console.ReadLine(); } } }
输出结果
上面代码的输出是
List1中的值: tiger lion dog List2中的值: tiger lion dog 不在List2中的List1中的值: lion dog
using System; using System.Collections.Generic; using System.Linq; namespace DemoApplication { class Program { static void Main(string[] args) { List<Fruit> fruitsList1 = new List<Fruit> { new Fruit { Name = "Apple", Size = "Small" }, new Fruit { Name = "Orange", Size = "Small" } }; Console.WriteLine($"List1中的值:"); foreach (var val in fruitsList1) { Console.WriteLine($"{val.Name}"); } List<Fruit> fruitsList2 = new List<Fruit> { new Fruit { Name = "Apple", Size = "Small" }, new Fruit { Name = "Mango", Size = "Small" } }; Console.WriteLine($"List2中的值:"); foreach (var val in fruitsList2) { Console.WriteLine($"{val.Name}"); } var fruitsList3 = fruitsList1.Where(f1 => fruitsList2.All(f2 => f2.Name != f1.Name)); Console.WriteLine($"List1中没有的值在List1中:"); foreach (var val in fruitsList3) { Console.WriteLine($"{val.Name}"); } Console.ReadLine(); } } public class Fruit { public string Name { get; set; } public string Size { get; set; } } }
输出结果
上面代码的输出是
List1中的值: Apple Orange List2中的值: Apple Mango List1中没有的值在List1中: Orange