원문 : http://dotnetperls.com/asenumerable


C# AsEnumerable Method



C# 프로그래밍 언어에서 IEnumerable 인터페이스는 제네릭 인터페이스로 열거 기능을 구현하는 인터페이스다. 제네릭 메서드인 AsEnumerable 메서드는 특정 타입을 IEnumerable 을 구현한 타입으로 변환시켜준다.


Unerstanding AsEnumerable

AsEnumerable 메소드는 확장 메서드(Extension Method) 이다. C# 3.0 에 추가된 문법이다. (처음 이 문법을 볼때 이게 어디 쓰일까 했는데 이제 슬슬 눈에 보이기 시작한다.) System.Linq 네임스페이스를 using 시켜야 사용할 수 있다.

한마디로, IEnumerable 컬렉션이 필요한 곳에 특정 데이터 타입이 IEnumerable 인터페이스를 구현하고 있지 않다면 AsEnumerable 확장 메서드를 이용하여 넘기는 것이다.

아래 예제 코드는 원문 블로그에 있는 예제 인데... array 은 원래 foreach 에 사용할 수 있는데...

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        // Create an array type.
        int[] array = new int[2];
        array[0] = 5;
        array[1] = 6;
        // Call AsEnumerable method.
        var query = array.AsEnumerable();
        foreach (var element in query)
        {
            Console.WriteLine(element);
        }
    }
}


.NET Framework 에서 AsEnumerable 의 구현 코드는 다음과 같다고 한다. 단지 파라미터를 캐스팅하여 리턴시켜주기만 한다.

public static IEnumerable<TSource> AsEnumerable<TSource>(this IEnumerable<TSource> source)
{
    return source;
}

예제 코드에서는 var 타입을 사용하였다. var 타입을 사용함으로써 코드를 깔끔(?!) 하게 만들 수 있다. 저 위치에는 IEnumerable<int> 타입을 명시적으로 사용할수도 있다.

Posted by six605
,