Linq查询

LINQ简称语言集成查询,设计的目的是为了解决在.NET平台上进行统一的数据查询。

1.一系列的扩展方法,比如:Where,Max,Select,Sum,Any,Average,All,Concat等都是针对IEnumerable的对象进行扩展的,也就是说,只要实现了IEnumerable接口,就可以使用这些扩展方法,来看看这段代码:      

List<int> arr = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
var result = arr.Where(a => { return a > 3; }).Sum();
Console.WriteLine(result);
Console.ReadKey();
<1>Where扩展方法,需要传入一个Func<int,bool>类型的泛型委托

        这个泛型委托,需要一个int类型的输入参数和一个布尔类型的返回值

        我们直接把a => { return a > 3; }这个lambda表达式传递给了Where方法

        a就是int类型的输入参数,返回a是否大于3的结果。

<2>Sum扩展方法计算了Where扩展方法返回的集合的和。

 

上面的代码中

      arr.Where(a => { return a > 3; }).Sum();

      这一句完全可以写成如下代码:

      (from v in arr where v > 3 select v).Sum();

      而且两句代码的执行细节是完全一样的

大家可以看到,第二句代码更符合语义,更容易读懂

      第二句代码中的where,就是我们要说的查询操作符。

2.Linq图解教程

http://www.cnblogs.com/jfzhu/archive/2013/01/01/2841332.html

3.Linq——扩展方法

声明扩展方法步骤:

创建一个名为ExtendHelper的类,约定了此类中的方法均是扩展方法。注意这个类必须是静态类(Static)
扩展方法必须是Static静态方法
第一个参数为待扩展的类型,前面标注this
如果ExtendHelper在一个类库中,记得对其添加引用并using相关名称空间

定义扩展方法需要注意,只能在静态类中定义并且是静态方法,如果扩展方法名和原有方法名发生冲突,那么扩展方法将失效。

 1 public static class ExtendHelper
 2     {
 3         public static string ToMyUpper(this string helper)
 4         {
 5             return "\"" + helper.ToUpper() + "\"";
 6         }
 7 
 8         public static string Quoted(this string helper, string a, string b)
 9         {
10             return a + helper + b;
11         }
12         public static bool IsNumber(this string helper)
13         {
14             int i;
15             return int.TryParse(helper, out i);
16         }
17         public static string ToChineses(this bool helper)
18         {
19             return helper ? "" : "";
20         }
21         public static int CreateMan(this Person helper)
22         {
23             Person one = new Person { Age = 18, Name = "Eyes" };
24             return one.Age;
25         }
26     }
27     public class Person
28     {
29         public int Age { get; set; }
30         public string Name { get; set; }
31     }
扩展方法
调用:
     Person p = new Person();
     Console.WriteLine(p.Name.IsNumber().ToChineses());
     Console.ReadKey();

  输出结果:假

 

http://www.cnblogs.com/jfzhu/archive/2013/01/01/2841332.html

4.Linq——查询与法

 

你可能感兴趣的:(Linq查询)