LINQ(一)

                        LINQ()

什么是linq
  LINQ
就是 Lanuage integrated Query(语言集合查询)

     我们一般查询sql server数据库的时候都需要 sql 语言 xml 查询需要 xml的查询

语言 对于webserivce 查询需要webservice 可能比较麻烦。

      对于复杂的sql 语句的话 ide在编译的时候并不能检测出来

 Linq 是一种 ORM 对于熟悉hibernate 的人来说 很容易理解

 数据不是直接连数据库而是通过 linq 这个数据层来处理 把数据最为面向对象的方式来处理,更符合面向对象的规范

 

. LINQ TO OBJECT 

2 下面看一段代码

using System;

using System.Linq;

using System.Collections;

using System.Collections.Generic;

 

namespace MyLinq

{

     public class LinqDemo01

     {

        static void Main()

        {

            int []  ints={0,1,3,2,5,6,9,8};

           

            var filerName=from num in ints where (num%2)==0

                        select  num;

           

            foreach(int num1 in filerName)

            {

               Console.Write(num1+"   ");

            }

           

           

        }

     }

}

这段代码是查询 数组中为偶数的字段。

大家想想  var filerName     var是什么类型呢?

其实var   Ienumerable 这种接口类型,微软规定 凡是实现Ienumerable 接口的类型都能用linq 查询

其实 ints 是一个数组 数组是实现着这用接口所以可以 linq

其实就是c# 2.0的迭代器  实现了 Ienumerable 接口的方法 Ienumerator 方法

就可以迭代了

 

 

    var filerName=from num in ints where (num%2)==0

                        select  num;

 

这个东西很像 SQL 语句

希望大家不要这样理解 其实他包含的内容很多

上面这条语句等同于下面的

IEnumerable<int> filer=ints.Where(i=>(i%2==0)).Select(i=>i);

大家可以吧这两句话互换  结果是一样的。。。。。。。。。。。。

其实linq 表达式就是一个lambda 表达式

对于int 数组int 没有 where 这个方法啊?

其实where是一int 数组  可以说是 实现 Ienumerable 接口的扩展方法(c# .3.0 语法糖)

对于lambda表达式 其实就是一个委托

 

 

Func<int ,bool> filter=delegate(int s){return s%2==0; };

Func<int ,int > project=delegate(int s){return s;};

 

IEnumerable<int> filer=ints.Where(filter).Select(project);

这样需要重新实现一个 迭代器 才可以工作

对于新技术都是老技术的整合 底层看起,在从抽象意义看起

 

posted @ 2009-09-21 23:53  fox_ice  阅读(130)  评论(0)    收藏  举报