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($"Values in List1:");
foreach (var val in animalsList1) {
Console.WriteLine($"{val}");
}
List<string> animalsList2 = new List<string> {
"tiger", "cat", "deer"
};
Console.WriteLine($"Values in List2:");
foreach (var val in animalsList1) {
Console.WriteLine($"{val}");
}
var animalsList3 = animalsList1.Except(animalsList2);
Console.WriteLine($"Value in List1 that are not in List2:");
foreach (var val in animalsList3) {
Console.WriteLine($"{val}");
}
Console.ReadLine();
}
}
} 출력
위 코드의 출력은
Values in List1: tiger lion dog Values in List2: tiger lion dog Value in List1 that are not in List2: lion dog
Where 절 사용 예
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($"Values in 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($"Values in List2:");
foreach (var val in fruitsList2) {
Console.WriteLine($"{val.Name}");
}
var fruitsList3 = fruitsList1.Where(f1 => fruitsList2.All(f2 => f2.Name != f1.Name));
Console.WriteLine($"Values in List1 that are not in List2:");
foreach (var val in fruitsList3) {
Console.WriteLine($"{val.Name}");
}
Console.ReadLine();
}
}
public class Fruit {
public string Name { get; set; }
public string Size { get; set; }
}
} 출력
위 코드의 출력은
Values in List1: Apple Orange Values in List2: Apple Mango Values in List1 that are not in List2: Orange