Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# List에서 지정된 조건과 일치하는 요소가 있는지 확인하는 방법

C#에서 List에 지정된 조건과 일치하는 요소가 하나라도 포함되어 있는지 확인하려면 Exists() 메서드를 사용하면 됩니다. 이 메서드는 Predicate<T> 형식의 조건식을 인수로 받으며, 목록 안에 조건을 만족하는 요소가 존재하면 true, 하나도 없으면 false를 반환합니다.

예제 1: 3의 배수 여부 확인

using System;
using System.Collections.Generic;
public class Demo {
   private static bool demo(int i) {
      return ((i % 3) == 0);
   }
   public static void Main(String[] args) {
      List<int> list = new List<int>();
      list.Add(255);
      list.Add(315);
      list.Add(410);
      list.Add(500);
      list.Add(600);
      list.Add(710);
      list.Add(800);
      list.Add(1000);
      Console.WriteLine("List elements...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
      Console.WriteLine("Does some elements match the predicate = "+list.Exists(demo));
   }
}

출력 결과

List elements...
255
315
410
500
600
710
800
1000
Does some elements match the predicate = True

위 예제에서는 각 요소가 3으로 나누어 떨어지는지 검사하는 조건식 (i % 3) == 0을 정의했습니다. 목록의 255, 315, 600이 3의 배수에 해당하므로 Exists() 메서드는 True를 반환합니다.

예제 2: 7의 배수 여부 확인

using System;
using System.Collections.Generic;
public class Demo {
   private static bool demo(int i) {
      return ((i % 7) == 0);
   }
   public static void Main(String[] args) {
      List<int> list = new List<int>();
      list.Add(255);
      list.Add(310);
      list.Add(410);
      list.Add(500);
      list.Add(600);
      Console.WriteLine("List elements...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
      Console.WriteLine("Does some elements match the predicate = "+list.Exists(demo));
   }
}

출력 결과

List elements...
255
310
410
500
600
Does some elements match the predicate = False

이번에는 조건식을 (i % 7) == 0으로 변경하여 7의 배수를 찾도록 했습니다. 목록의 모든 요소가 7로 나누어 떨어지지 않기 때문에 결과는 False입니다.

정리

List<T>.Exists(Predicate<T>) 메서드는 컬렉션 전체를 순회하다가 조건을 만족하는 첫 번째 요소를 발견하는 즉시 true를 반환하고 탐색을 중단하므로 효율적입니다. 또한 람다 식을 활용하면 별도의 메서드를 정의하지 않고도 list.Exists(x => x % 3 == 0)처럼 더 간결하게 코드를 작성할 수 있습니다.