Share via


How to: Return a Query from a Method (C# Programming Guide)

This example shows how to return a query from a method in the return value and as an out parameter.

Any query must have a type of IEnumerable or IEnumerable<T>, or a derived type such as IQueryable<T>. Therefore any return value or out parameter of a method that returns a query must also have that type. If a method materializes a query into a concrete List<T> or Array type, it is considered to be returning the query results instead of the query itself. A query variable returned from a method can still be composed or modified.

For an example of how to execute a query that is passed to a method, see the Object Dumper Sample.

Example

In the following example, the first method returns a query as a return value, and the second method returns a query as an out parameter. Note that in both cases, it is a query and not query results that are being returned.

class MQ
{
    IEnumerable<string> QueryMethod1(ref int[] ints)
    {
        var intsToStrings = from i in ints
                            where i > 4
                            select i.ToString();
        return intsToStrings;
    }

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

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

        var myQuery = app.QueryMethod1(ref nums);


        //execute myQuery 
        foreach (string s in myQuery)
        {
            Console.WriteLine(s);
        }

        //modify myQuery
        myQuery = (from str in myQuery
                   orderby str descending 
                   select str).
                  Take(3);

        // Executing myQuery after more 
        // composition
        Console.WriteLine("After modification:");
        foreach (string s in myQuery)
        {
            Console.WriteLine(s);
        }

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

Compiling the Code

  • Create a Visual Studio project that targets the .NET Framework version 3.5. By default, the project has a reference to System.Core.dll and a using directive for the System.Linq namespace.

  • Copy the code into your project.

  • Press F5 to compile and run the program.

  • Press any key to exit the console window.

See Also

Concepts

LINQ Query Expressions (C# Programming Guide)