LINQ从方法中返回查询

此示例演示如何以返回值和输出参数的形式从方法中返回查询。

任何查询的类型都必须为 IEnumerable 或 IEnumerable<(Of <(T>)>),或一种派生类型(如 IQueryable<(Of <(T>)>))。因此,返回查询的方法的任何返回值或输出参数也必须具有该类型。如果某个方法将查询具体化为具体的 List<(Of <(T>)>) 或 Array 类型,则认为该方法在返回查询结果(而不是查询本身)。仍然能够编写或修改从方法中返回的查询变量。

在下面的示例中,第一个方法以返回值的形式返回查询,第二个方法以输出参数的形式返回查询。请注意,在这两种情况下,返回的都是查询,而不是查询结果。

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();
    }
}

结果为:

5
6
7
8
9
After modification:
9
8
7
Press any key to exit.

tmp2E

posted @ 2008-07-01 20:47  superfang  阅读(2496)  评论(1编辑  收藏  举报