欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

LINQ从方法中返回查询

发布时间:2025/3/21 31 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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.

转载于:https://www.cnblogs.com/superfang/archive/2008/07/01/1233535.html

总结

以上是生活随笔为你收集整理的LINQ从方法中返回查询的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。