C#/LINQ

[C#]LINQ 특정 조건을 만족하는지 체크하는 방법 - All, Any 메서드

DevStory 2022. 7. 24.

Quantifiers 연산

Quantifiers 연산은 컬렉션과 같은 데이터 집합에서 모든 요소들이 특정 조건을 만족하는지 확인할 수 있는 방법들을 제공합니다.

 

Quantifiers 연산에서 제공하는 메서드인 All(), Any(), Contains() 메서드는 특정 조건을 만족하면 true를 반환하고 그렇지 않으면 false를 반환합니다.

 

All() 메서드

데이터 집합의 모든 요소가 주어진 조건을 만족하면 true를 반환하고 그렇지 않으면 false를 반환합니다.

 

Any() 메서드

데이터 집합의 요소 중 하나라도 특정 조건을 만족하면 true를 반환하고 그렇지 않으면 false를 반환합니다.

 

Contains() 메서드

데이터 집합에서 특정 값이 포함되어 있다면 true를 반환하고 그렇지 않으면 false를 반환합니다.

 

이번 포스팅은 All(), Any() 메서드에 대해 설명하며 Contains() 메서드 사용 방법은 아래 포스팅에서 확인할 수 있습니다.

 

[C#]LINQ 특정 값 포함 여부 - Contains 메서드

Contains 메서드 LINQ의 Contains() 메서드는 시퀀스 또는 컬렉션에 특정 요소가 포함되어 있는지 여부를 확인하기 위해 사용됩니다. 특정 요소가 존재하는 경우 true를 반환하고 그렇지 않으면 false를

developer-talk.tistory.com


All 메서드

위에서 설명했듯이 LINQ의 All() 메서드는 데이터 집합의 모든 요소가 특정 조건을 만족하는지 확인하기 위해 사용됩니다. 모든 요소가 특정 조건을 만족하면 true를 반환하고 그렇지 않으면 false를 반환합니다.

 

All() 메서드는 오버로드된 버전이 존재하지 않으며, 다음 소스 코드는 All() 메서드 구문입니다.

public static bool All<TSource>(
  this IEnumerable<TSource> source, 
  Func<TSource, bool> predicate);

All() 메서드는 System.Linq 네임스페이스의 Enumerable 클래스에 구현되어 있으며, IEnumerable 인터페이스의 확장 메서드입니다.


예제 1. int 타입의 List

다음 예제는 All() 메서드를 사용하여 int 타입의 List에서 10보다 큰 요소가 존재하는지 체크합니다.

class Program
{
  static void Main(string[] args)
  {
    List<int> intList = new List<int>()
    {
      5, 10, 15, 20, 25, 30
    };

    // 1. 질의 구문(Query Syntax)
    bool linqQueryResult = (from num in intList
                            select num).All(item => item > 10);

    // 2. 메서드 구문(Method Syntax)
    bool linqMethodResult = intList.All(item => item > 10);

    Console.WriteLine("질의 구문 결과: " + linqQueryResult);
    Console.WriteLine("메서드 구문 결과: " + linqMethodResult);
  }
}

[실행 결과]

질의 구문 결과: False
메서드 구문 결과: False

intList에는 10보다 작은 요소인 5가 존재하므로 All() 메서드는 false를 반환합니다.


예제 2. 사용자 정의 클래스

다음 예제는 사용자 정의 클래스인 Person 타입인 List에서 모든 요소가 다음 조건을 만족하는지 체크합니다.

- Name의 길이가 2보다 길고

- Age가 10보다 큰 경우

public class Person
{
  public string Name { get; set; }
  public int Age { get; set; }
  public override string ToString()
  {
    return "Name: " + Name + ", Age: " + Age;
  }
}

class Program
{
  static void Main(string[] args)
  {
    List<Person> personA = new List<Person>
    {
      new Person{Name ="Bob", Age = 20},
      new Person{Name ="Nick", Age = 30},
      new Person{Name ="Tom", Age = 40}
    };

    // 1. 질의 구문(Query Syntax)
    bool linqQueryResult = (from   person in personA
                            select person)
                            .All(item => item.Name.Length > 2 && item.Age > 10);

    // 2. 메서드 구문(Method Syntax)
    bool linqMethodResult = personA.All(item => item.Name.Length > 2 && item.Age > 10);

    Console.WriteLine("질의 구문 결과: " + linqQueryResult);
    Console.WriteLine("메서드 구문 결과: " + linqMethodResult);
  }
}

[실행 결과]

질의 구문 결과: True
메서드 구문 결과: True

Any 메서드

LINQ의 Any() 메서드는 데이터 집합의 요소 중 하나라도 특정 조건을 만족하면 true를 반환하고 그렇지 않으면 false를 반환합니다.

 

Any() 메서드는 두 가지 오버로드된 버전이 존재합니다.

public static bool Any<TSource>(
  this IEnumerable<TSource> source);

public static bool Any<TSource>(
  this IEnumerable<TSource> source, 
  Func<TSource, bool> predicate);

Any() 메서드는 System.Linq 네임스페이스의 Enumerable 클래스에 구현되어 있으며, IEnumerable 인터페이스의 확장 메서드입니다.

 

첫 번째 메서드는 매개변수가 존재하지 않으며, 두 번째 매개변수는 Func 대리자를 매개변수로 사용합니다.

 

매개변수가 존재하지 않은 Any() 메서드는 다음 예제처럼 데이터 집합의 요소 존재 유무를 판단하기 위해 사용할 수 있습니다.

class Program
{
  static void Main(string[] args)
  {
    List<int> intList1 = new List<int>(){};
    List<int> intList2 = new List<int>()
    {
        5, 10, 15, 20, 25, 30
    };

    bool linqMethodResult1 = intList1.Any();
    bool linqMethodResult2 = intList2.Any();

    Console.WriteLine("메서드 구문 결과: " + linqMethodResult1);
    Console.WriteLine("메서드 구문 결과: " + linqMethodResult2);
  }
}

[실행 결과]

메서드 구문 결과: False
메서드 구문 결과: True

예제 1. int 타입의 List

다음 예제는 Any() 메서드를 사용하여 int 타입의 List에서 10보다 작은 요소가 하나라도 있는지 확인합니다.

class Program
{
  static void Main(string[] args)
  {
    List<int> intList = new List<int>()
    {
       5, 10, 15, 20, 25, 30
    };

    // 1. 질의 구문(Query Syntax)
    bool linqQueryResult = (from num in intList
                            select num).Any(item => item < 10);

    // 2. 메서드 구문(Method Syntax)
    bool linqMethodResult = intList.Any(item => item < 10);

    Console.WriteLine("질의 구문 결과: " + linqQueryResult);
    Console.WriteLine("메서드 구문 결과: " + linqMethodResult);
  }
}

[실행 결과]

질의 구문 결과: True
메서드 구문 결과: True

예제 2. 사용자 정의 클래스

다음 예제는 사용자 정의 클래스인 Person 타입인 List에서 다음 조건을 만족하는 요소가 하나라도 존재하는지 확인합니다.

- Name의 길이가 3보다 길고

- Age가 40보다 큰 경우

public class Person
{
  public string Name { get; set; }
  public int Age { get; set; }
  public override string ToString()
  {
    return "Name: " + Name + ", Age: " + Age;
  }
}

class Program
{
  static void Main(string[] args)
  {
    List<Person> personA = new List<Person>
    {
        new Person{Name ="Bob", Age = 20},
        new Person{Name ="Nick", Age = 30},
        new Person{Name ="Tom", Age = 40}
    };

    // 1. 질의 구문(Query Syntax)
    bool linqQueryResult = (from   person in personA
                            select person)
                            .Any(item => item.Name.Length > 3 && item.Age > 40);

    // 2. 메서드 구문(Method Syntax)
    bool linqMethodResult = personA.Any(item => item.Name.Length > 3 && item.Age > 40);

    Console.WriteLine("질의 구문 결과: " + linqQueryResult);
    Console.WriteLine("메서드 구문 결과: " + linqMethodResult);
  }
}

[실행 결과]

질의 구문 결과: False
메서드 구문 결과: False
반응형

댓글