CSharp linq 的本质
linq 的本质是扩展方法和委托的结合
链式 linq 和 方法级linq
  List<int> list = new List<int>() {
                3,9,32,7
            };
            // linq 分为链式 和方法级linq
            //链式的写法如下
            var q = from temp in list where temp > 6 select temp;
            //方法级linq 如下
            var q1 = list.Where(temp => temp > 6).Select(temp=>temp);
            //通过反编译可以看出链式linq 最终都是要翻译为方法级linq  ,这点可以大伙可以自行尝试
自定义自己的linq查询
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int>() {
                3,9,32,7
            };
            //找出大于6 的数,我们很自然的会使用linq 来查询
            var newList = list.Where(x => x > 6);
            //linq 的本质是什么呢? linq的本质是 扩展方法和委托的结合
            var newList2 = list.CustomerWhere(x => x > 6);
            foreach (var item in newList)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("---------------");
            foreach (var item in newList2)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }
    /// <summary>
    /// 自定义一个扩展方法, 要点:静态类的静态方法,this 要扩展的类型   其余参数
    /// </summary>
    static class CustomerWhereExtension
    {
        public static List<int> CustomerWhere(this List<int> list, Func<int, bool> predict)
        {
            List<int> tempList = new List<int>();
            foreach (var item in list)
            {
                if (predict.Invoke(item))
                {
                    tempList.Add(item);
                }
            }
            return tempList;
        }
    }
}
运行结果如下

 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号