Lambda表达式

  • 本质是个方法
  • 在使用lambda表达式时,编译器会在在使用lambda表达式中的类会产生一个类中类
  • 每一个lambda表达式对应类中类中静态委托
  • 实际上是类中类里面的一个internal方法,会被绑定在类中类的静态委托

QQ截图20200527094012.png
QQ截图20200527094758.png

陈述式语法查询

  1. class Student
  2. {
  3. string name {get; set;}
  4. int id {get; set;}
  5. int age {get; set;}
  6. }
  7. public static class ExtendMethod
  8. {
  9. //基于委托封装解耦
  10. //泛型
  11. public List<T> IWhere<T>(this List<T> source, Func<List<T>, bool> func)
  12. {
  13. var list = new List<T>();
  14. foreach(var item in source)
  15. {
  16. if (func.Invoke())
  17. {
  18. list.Add(item);
  19. }
  20. }
  21. return list;
  22. }
  23. //迭代器,按需获取
  24. public IEnumerable<T> MyWhere<T>(this IEnumerable<T> source, Func<List<T>, bool> func)
  25. {
  26. if (source == null)
  27. {
  28. throw new Exception("source is null")
  29. }
  30. if (func == null)
  31. {
  32. throw new Exception("func is null")
  33. }
  34. foreach(var item in source)
  35. {
  36. if (func.Invoke())
  37. {
  38. yield item;
  39. }
  40. }
  41. }
  42. }
  43. var result = list.MyWhere<Student>(s => s.Age < 30)

Linq to object(Enumerable)

  • 是一个扩展方法
  • 返回迭代器
  • 与上个例子类似
  • 基于委托封装解耦,去掉重复代码,完成通用代码
  • 泛型
  • 加上迭代器,按需加载 ```csharp //查询表达式 var list = from s in studentList
    1. where s.Age < 30
    2. select s;
    //最终会翻译成以下结果 var linqWhere = list.Where(s => s.Age < 30) .Select(s => s.Name.Length);
  1. <a name="8M6lV"></a>
  2. ## Where
  3. - 完成对数据集合的过滤,通过委托封装完成通用代码,泛型和迭代器去提供特性
  4. ```csharp
  5. var linqWhere = list.Where<Student>(s => s.Age < 30);

Select

  • 完成对数据集合的转换,通过委托封装完成通用代码,泛型和迭代器去提供特性

QQ截图20200528123641.png

  1. var linqWhere = list.Where<Student>(s => s.Age < 30)
  2. .Select<Student, int>(s => s.Name.Length);
  3. var linqWhere = list.Where<Student>(s => s.Age < 30)
  4. .Select(s => new
  5. {
  6. Id = s.Id,
  7. Name = s.Name;
  8. Length = s.Name.Length
  9. });

Linq to sql(Queryable)

  • 封装了通用代码(ADO.NET)
  • 表达式目录树解析SQL