LINQ의 수량자 작업(C#)

수량자 작업은 시퀀스에서 조건을 충족하는 요소가 일부인지 전체인지를 나타내는 Boolean 값을 반환합니다.

다음 그림은 두 개의 서로 다른 소스 시퀀스에 대한 두 개의 서로 다른 수량자 작업을 보여 줍니다. 첫 번째 작업에서는 요소 중 문자 ‘A’가 있는지 묻습니다. 두 번째 작업에서는 모든 요소가 문자 ‘A’인지 묻습니다. 이 예에서는 두 메서드 모두 true를 반환합니다.

LINQ 수량자 작업

메서드 이름 설명 C# 쿼리 식 구문 추가 정보
모두 시퀀스의 모든 요소가 조건을 만족하는지를 확인합니다. 해당 없음. Enumerable.All
Queryable.All
모두 시퀀스의 임의의 요소가 조건을 만족하는지를 확인합니다. 해당 없음. Enumerable.Any
Queryable.Any
포함 시퀀스에 지정된 요소가 들어 있는지를 확인합니다. 해당 없음. Enumerable.Contains
Queryable.Contains

모두

다음 예제에서는 All을 사용하여 모든 시험에서 70점 이상의 점수를 받은 학생을 찾습니다.

IEnumerable<string> names = from student in students
                            where student.Scores.All(score => score > 70)
                            select $"{student.FirstName} {student.LastName}: {string.Join(", ", student.Scores.Select(s => s.ToString()))}";

foreach (string name in names)
{
    Console.WriteLine($"{name}");
}

// This code produces the following output:
//
// Cesar Garcia: 71, 86, 77, 97
// Nancy Engström: 75, 73, 78, 83
// Ifunanya Ugomma: 84, 82, 96, 80

모두

다음 예제에서는 이 방법을 사용하여 Any 모든 시험에서 95점보다 큰 점수를 받은 학생을 찾습니다.

IEnumerable<string> names = from student in students
                            where student.Scores.Any(score => score > 95)
                            select $"{student.FirstName} {student.LastName}: {student.Scores.Max()}";

foreach (string name in names)
{
    Console.WriteLine($"{name}");
}

// This code produces the following output:
//
// Svetlana Omelchenko: 97
// Cesar Garcia: 97
// Debra Garcia: 96
// Ifeanacho Jamuike: 98
// Ifunanya Ugomma: 96
// Michelle Caruana: 97
// Nwanneka Ifeoma: 98
// Martina Mattsson: 96
// Anastasiya Sazonova: 96
// Jesper Jakobsson: 98
// Max Lindgren: 96

포함

다음 예제에서는 Contains를 사용하여 시험에서 정확힌 95점을 받은 학생을 찾습니다.

IEnumerable<string> names = from student in students
                            where student.Scores.Contains(95)
                            select $"{student.FirstName} {student.LastName}: {string.Join(", ", student.Scores.Select(s => s.ToString()))}";

foreach (string name in names)
{
    Console.WriteLine($"{name}");
}

// This code produces the following output:
//
// Claire O'Donnell: 56, 78, 95, 95
// Donald Urquhart: 92, 90, 95, 57

참고 항목