LINQ Any와 All로 조건을 확인하는 방법: C#

약 1분 읽기 LINQ Any와 All로 조건을 확인하는 방법: C# 대표 이미지

LINQ

수량자(?) Quantifiers

이상하게도 마이크로소프트 공식 번역은 ‘수량자’지만 수량과는 전혀 상관이 없습니다. Any 메서드는 집합 안에 조건에 맞는 요소가 하나라도 있는지 확인하는 메서드이고, All 메서드는 집합 안에 모든 요소가 조건에 맞는지 확인하는 메서드입니다.

하나라도 조건에 맞는 요소가 있는지 확인하기

string[] words = { "believe", "relief", "receipt", "field" };

            bool iAfterE = words.Any(w => w.Contains("ei"));

            // iAfterE = true;

words 배열 안에 “receipt” 는 “ei”를 포함하므로 iAfterE 는 true 가 됩니다.

모든 요소가 조건에 맞는지 확인하기

int[] numbers = { 1, 11, 3, 19, 41, 65, 19 };

            bool onlyOdd = numbers.All(n => n % 2 == 1);

            // onlyOdd = true;

numbers 배열에 홀수인 숫자 밖에 존재하지 않으므로 onlyOdd 는 true 가 됩니다.

Group 별로 확인하기

그룹 별로 조건에 맞는 요소가 있는지 확인할 수 있습니다.

List

products = GetProductList(); var productGroups = from p in products group p by p.Category into g where g.Any(p => p.UnitsInStock == 0) select (Category: g.Key, Products: g); ``` 그룹 별로 그룹 내 모든 요소가 조건에 맞는지 확인할 수도 있습니다.

List products = GetProductList();

        var productGroups = from p in products
                            group p by p.Category into g
                            where g.All(p => p.UnitsInStock > 0)
                            select (Category: g.Key, Products: g)