上一篇说了 from in select 的本质,具体参见。本篇说下 from...in... from... in... select
首先上一段代码,猜猜结果是什么?
- class Program {
- static void Main(string[] args) {
- /*var result = from s in new TestApp() { A = 2 } select s;*/
- var result1 = from s in new TestApp() {
- A = 2
- }
- from i in (s + 2).ToString() select(Convert.ToInt32(i) + s).ToString();
- Console.WriteLine(result1.GetType() + " " + result1);
- Console.ReadLine();
- }
- }
- public class TestApp {
- public int A {
- get;
- set;
- }
- }
这段代码的运行结果是什么呢?
答案是,这段代码会报错,根本编译不过~~~~~~ 那么按照上一篇,我们对 TestApp 进行方法扩展呢?那扩展 Select 扩展方法,发现依旧变异不过。最后查 linq 的 api,发现了一个叫 SelectMany 的方法。在结合 SelectMany 的用法我们可以猜测应该是这个扩展方法。于是我对 TestApp 进行了如下扩展,
- public static class SelectExtension {
- public static string Select(this TestApp app, Func < int, int > selector) {
- return "hello,你是" + selector(app.A).ToString();
- }
- public static string SelectMany(this TestApp app, Func < int, string > fun1, Func < int, string, string > fun2) {
- var j = fun1(app.A);
- return "hello,你真是" + fun2(app.A, j);
- }
- }
编译,运行,结果如下:
那么最后我们需要猜测 SelectMany 的通用方法是什么,也就是 SelectMany 到底是怎么定义的呢?
public static T SelectMany<T1,T2,T3,T>(this TestApp app, Func<T1, T2> fun1, Func<T1, T2, T3> fun2){}
经过验证发现推论是那么完美,只要扩展方法,代码完美运行。
不过悲剧也发生了,from...in... from... in... from... in... select,三重循环该如何重载呢还是方法吗?我完全找不到北了,编译不成功,扩展失败,这是一个悲剧,希望知道的人告诉我结果~~~~~~~
来源: http://www.cnblogs.com/watermoon2/p/linq.html