30 확장 메서드(2)

vencott·2021년 6월 2일
0

C#

목록 보기
30/32

Enumerable 확장 메서드의 예제

System.Linq.Enumerable 클래스는 LINQ 쿼리에서 사용되는 많은 확장 메서드들을 포함하는 클래스이다

첫번째 파라미터는 이 메서드가 Ienumerable 인터페이스를 지원하는 모든 Type에 사용된다는 것을 의미한다

두번째 파라미터는 Func라는 Delegate를 받아들인다는 것을 의미하는데, 주로 LINQ 쿼리를 람다식으로 표현하여 넣는다

// LINQ에 정의된 Where 확장메서드
public static IEnumerable<TSource> Where<TSource>(
    this IEnumerable<TSource> source, 
    Func<TSource, bool> predicate
)
// Where 확장메서드를 List<T>에서 사용
List<string> list = new List<string> { "Apple", "Grape", "Banana" };
IEnumerable<string> q = list.Where(p => p.StartsWith("A"));
static void Main(string[] args)
{
   List<int> nums = new List<int> { 55, 44, 33, 66, 11 };

   // Where 확장메서드를 정수List에 사용
   var v = nums.Where(p => p % 3 == 0);

   // IEnumerable<int> 결과를 정수List로 변환
   List<int> arr = v.ToList<int>();

   // 출력
   arr.ForEach(n => Console.WriteLine(n));
}

출처: http://www.csharpstudy.com/

profile
Backend Developer

0개의 댓글