다음을 통해 공유


방법: 메서드에서 쿼리 반환(C# 프로그래밍 가이드)

업데이트: 2010년 7월

이 예제에서는 메서드의 쿼리를 반환 값 및 out 매개 변수로 반환하는 방법을 보여 줍니다.

모든 쿼리는 IEnumerable 또는 IEnumerable<T> 형식이거나 IQueryable<T>과 같은 파생 형식이어야 합니다. 따라서 쿼리를 반환하는 메서드의 모든 반환 값 또는 out 매개 변수도 이와 같은 형식이어야 합니다. 메서드에서 쿼리를 List<T> 또는 Array 형식으로 구체화할 경우 해당 메서드는 쿼리 자체가 아니라 쿼리 결과를 반환하는 것으로 간주됩니다. 메서드에서 반환되는 쿼리 변수는 구성 또는 수정이 가능합니다.

예제

다음 예제에서 첫 번째 메서드는 쿼리를 반환 값으로 반환하고 두 번째 메서드는 쿼리를 out 매개 변수로 반환합니다. 두 경우 모두 반환되는 것은 쿼리 결과가 아니라 쿼리 자체입니다.

class MQ
{
    // QueryMethhod1 returns a query as its value.
    IEnumerable<string> QueryMethod1(ref int[] ints)
    {
        var intsToStrings = from i in ints
                            where i > 4
                            select i.ToString();
        return intsToStrings;
    }

    // QueryMethod2 returns a query as the value of parameter returnQ.
    void QueryMethod2(ref int[] ints, out IEnumerable<string> returnQ)
    {
        var intsToStrings = from i in ints
                            where i < 4
                            select i.ToString();
        returnQ = intsToStrings;
    }

    static void Main()
    {
        MQ app = new MQ();

        int[] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

        // QueryMethod1 returns a query as the value of the method.
        var myQuery1 = app.QueryMethod1(ref nums);

        // Query myQuery1 is executed in the following foreach loop.
        Console.WriteLine("Results of executing myQuery1:");
        // Rest the mouse pointer over myQuery1 to see its type.
        foreach (string s in myQuery1)
        {
            Console.WriteLine(s);
        }

        // You also can execute the query returned from QueryMethod1 
        // directly, without using myQuery1.
        Console.WriteLine("\nResults of executing myQuery1 directly:");
        // Rest the mouse pointer over the call to QueryMethod1 to see its
        // return type.
        foreach (string s in app.QueryMethod1(ref nums))
        {
            Console.WriteLine(s);
        }


        IEnumerable<string> myQuery2;
        // QueryMethod2 returns a query as the value of its out parameter.
        app.QueryMethod2(ref nums, out myQuery2);

        // Execute the returned query.
        Console.WriteLine("\nResults of executing myQuery2:");
        foreach (string s in myQuery2)
        {
            Console.WriteLine(s);
        }


        // You can modify a query by using query composition. A saved query
        // is nested inside a new query definition that revises the results
        // of the first query.
        myQuery1 = from item in myQuery1
                   orderby item descending
                   select item;

        // Execute the modified query.
        Console.WriteLine("\nResults of executing modified myQuery1:");
        foreach (string s in myQuery1)
        {
            Console.WriteLine(s);
        }

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
} 

코드 컴파일

  • .NET Framework 버전 3.5 이상을 대상으로 하는 Visual Studio 프로젝트를 만듭니다. 기본적으로 프로젝트에는 System.Core.dll에 대한 참조 및 System.Linq 네임스페이스에 대한 using 지시문이 있습니다.

  • 클래스를 예제의 코드로 바꿉니다.

  • F5 키를 눌러 프로그램을 컴파일하고 실행합니다.

  • 아무 키나 눌러 콘솔 창을 닫습니다.

참고 항목

개념

LINQ 쿼리 식(C# 프로그래밍 가이드)

변경 기록

날짜

변경 내용

이유

2010년 7월

예제에 QueryMethod2가 추가되었습니다. 설명 주석이 보강되었습니다.

고객 의견