C#/LINQ

[C#]LINQ 특정 조건을 만족하는 데이터 가져오기 - TakeWhile 메서드

DevStory 2022. 8. 11.

TakeWhile 메서드

C#의 Linq에서 제공하는 TakeWhile() 메서드는 데이터 집합의 데이터를 처음 위치에서 순회합니다. 데이터 집합을 순회하는 동안 TakeWhile() 메서드에 전달된 조건문의 결과가 false인 경우 반복문을 중단하고 반복문이 실행되는 동안 조건을 충족했던 데이터를 반환합니다.

 

System.Linq 네임스페이스에 존재하는 TakeWhile() 메서드는 두 가지 오버로드된 버전이 존재합니다.

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

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

TakeWhile() 메서드의 매개변수는 동일하지만, 두 번째 매개변수인 Func 대리자의 매개변수가 다른 것을 확인할 수 있습니다.

 

첫 번째 TakeWhile() 메서드의 Func 대리자는 데이터 집합의 요소만 접근할 수 있습니다. 두 번째 TakeWhile() 메서드의 Func 대리자는 데이터 집합의 요소와 인덱스를 접근할 수 있습니다.


예제 1. int 타입의 List

다음 예제는 1부터 10까지 int 타입의 값을 가지는 List에서 TakeWhile() 메서드를 호출합니다. TakeWhile() 메서드에는 값이 5보다 작은 경우 true를 반환하고 그렇지 않으면 false를 반환하는 조건문을 전달합니다.

class Program
{
  static void Main(string[] args)
  {
    List<int> intList = new List<int>()
    {
      1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    };

    List<int> TakeWhileResult = intList.TakeWhile(num => num < 5).ToList();

    foreach(int num in TakeWhileResult)
    {
      Console.WriteLine(num);
    }
  }
}

[실행 결과]

1
2
3
4

예제 2. 질의 구문에서 TakeWhile 메서드 호출

질의 구문에는 TakeWhile() 메서드를 지원하지 않습니다. 따라서, 메서드 구문과 혼합하여 사용합니다.

class Program
{
  static void Main(string[] args)
  {
    List<int> intList = new List<int>()
    {
      1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    };

    List<int> TakeWhileResult = (from   num in intList
                                 select num).TakeWhile(num => num < 5).ToList();

    foreach (int num in TakeWhileResult)
    {
      Console.WriteLine(num);
    }
  }
}

[실행 결과]

1
2
3
4

예제 3. Where절과 TakeWhile 메서드의 차이점

다음 예제는 Where절과 TakeWhile() 메서드의 차이점을 보여줍니다.

class Program
{
  static void Main(string[] args)
  {
    List<int> intList = new List<int>()
    {
      1, 2, 3, 4, 5, 1, 2, 3, 4, 5
    };

    List<int> TakeWhileResult = intList.TakeWhile(num => num < 5).ToList();

    Console.WriteLine("TakeWhile() 메서드 결과");
    foreach (int num in TakeWhileResult)
    {
      Console.Write(num + " ");
    }

    List<int> WhereResult = intList.Where(num => num < 5).ToList();

    Console.WriteLine("\nWhere절 결과");
    foreach (int num in WhereResult)
    {
      Console.Write(num + " ");
    }
  }
}

[실행 결과]

TakeWhile() 메서드 결과
1 2 3 4
Where절 결과
1 2 3 4 1 2 3 4

TakeWhile() 메서드

- 데이터 집합의 처음 위치에서 반복문을 시작하여 TakeWhile() 메서드에 전달된 조건문이 false인 경우 반복문이 중단되고 데이터 집합을 순회하는 동안 조건문을 충족했던 데이터를 반환합니다.

 

Where절

- 조건을 만족하는 모든 데이터를 반환합니다.


예제 4. 인덱스를 매개변수로 가지는 TakeWhile 메서드

다음 예제는 Func 대리자에서 인덱스를 매개변수로 가지는 TakeWhile() 메서드를 사용합니다. index가 3보다 작으면 true를 반환하는 조건문을 TakeWhile() 메서드에 전달합니다.

class Program
{
  static void Main(string[] args)
  {
    List<string> strList = new List<string>()
    {
      "One", "Two", "Three", "Four", "Five"
    };

    List<string> TakeWhileResult = strList
                                   .TakeWhile((strValue, index) => index < 3)
                                   .ToList();

    foreach (string value in TakeWhileResult)
    {
      Console.WriteLine(value);
    }
  }
}

[실행 결과]

One
Two
Three
반응형

댓글