LinQ技术

来源:互联网 发布:全球人工智能十强公司 编辑:程序博客网 时间:2024/05/20 11:50

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  

namespace LINQ技术  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            //LINQ中的Where扩展方法,要想使用,必须导入using System.Linq;   
            //下面我们看一下这个方法的声明   
            //public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source,Func<TSource, bool> predicate )   
            //返回类型是:IEnumerable<TSource>   
            //第一参数this IEnumerable<TSource> source代表的是他要扩展的类型,也就是说在IEnumerable<TSource>可以直接调用where方法   
            //Func<TSource, bool> predicate第二个参数是一个委托,下面我们看一下他的声明   
            //public delegate TResult Func<T, TResult>( T arg ) 封装一个带有T类型,返回Tresult类型的方法   
            //下面我们使用Linq中的Where方法来检索我们的列表   
            //我们做一个List<T>的列表,其中存放Person对象,然后我们用where方法检索出年纪在20-30之前的人员 。   
            List<Person> lists = new List<Person>() ;  

            lists.Add( new Person( "aladdin" , 30 ) ) ;  
            lists.Add( new Person( "jacky" , 20 ) ) ;  
            lists.Add( new Person( "zhao" , 11 ) ) ;  
            lists.Add( new Person( "fuck" , 33 ) ) ;  
            lists.Add( new Person( "emep" , 25 ) ) ;  

            IEnumerable<Person> reList = lists.Where<Person>( param => param.age >= 20 && param.age<= 30 ) ;  

            foreach( Person per in reList )  
            {  
                Console.WriteLine( per.name + " " + per.age ) ;  
            }  
            //结果 aladdin jacky   

            //其实Linq一般的查询,是可以直接写where select 等语句来实现,系统编译时,会自动将他转化成扩展方法的调用   
            var query = from r in lists where r.age >= 20 && r.age <= 30 select r;  

            foreach( Person per in query )  
            {  
                Console.WriteLine( per.name + " " + per.age ) ;  
            }  

            //linq语句必须是以from开头,以select 或者 group结尾巴   
            //注意,query变量,只是指定了一个查询方式,并没有执行,真正的执行其实是在foreach时才产生的   

            //推迟查询的执行   
            //推迟查询的执行也就是说查询是在跌代时才执行的,不是var query中,下面我们来用代码证实   

            Console.WriteLine( "增加新内容后的输出--------------") ;  
            lists.Add( new Person( "newaladdin" , 22 ) ) ;  
            //我们增加了一个新对象,22岁,明显是符合条件的,下面我们二次跌代   
            foreach( Person per in query )  
            {  
                Console.WriteLine( per.name + " " + per.age ) ;  
            }  
            //可以看出,第二次跌代完全可以接触到新对象,而我们并没有定义新的query 这就是推迟查执行   


            Console.ReadLine() ;  
        }  

        class Person  
        {  
            public string name ;  
            public int age ;  

            public Person( string name , int age )  
            {  
                this.name = name ;  
                this.age = age ;  
            }  
        }  
    }  
}