C#学习笔记(6)

在我们编写一个带有存储数据的功能的程序的时候,总免不了要与数据库打交道,于是LINQ(语言集成查询)就应运而生了。LINQ是一组C#和VB的语言拓展,它允许编写C#或者VB代码以查询数据库相同的方式操作内存数据。

与一般的SQL语言不同的,用户在使用LINQ语言的时候可以自定义数据类型,这样就为程序员们提供了很大的便利,LINQ中包含40多个查询操作,其基本语法与SQL相同

from ...
where ...
select ...

唯一与SQL语言不同的要数select语句的位置了,LINQ之所以把from语句放在最前面,是为了方便让编译器识别select语句中的数据的类型,这样才能使IDE中的智能感知功能更好的发挥作用。

现在来举例说明一下LINQ的用法

    public class Date
    {
        public int day { get; set; }
        public int month { get; set; }
        public int year { get; set; }
        public override string ToString()
        {
            return string.Format("{0} {1} {2}",
                        year, month, day);
        }

    }

创建一个Date类来存储日期

        private  static  List<Date> CreateDateList()
        {
           List<Date> date = new List<Date>
           {
                  new Date { year = 2015,month = 4,
                                                day = 27},
                  new Date { year = 2000, month = 7,
                                                day = 23 },
                  new Date { year = 1900, month = 12,
                                                day = 31 },
                  new Date { year = 2007, month = 1,
                                                day = 1 },
                  new Date { year = 2055, month = 2,
                                                day = 28 }
            };
            return date;
         }

创建若干日期用于查询

我们从最简单的查询开始,查询所有的Date类型的数据

 List<Date> date =Date.CreateDateList();
IEnumerable<Date> result =  from  dt in date
select dt;
foreach (Date d in result)
{    Console.WriteLine(d.ToString());}

输出结果如下

 现在我们来加上where语句,选择year==2007的date数据

List<Date> date =Date.CreateDateList();
IEnumerable<Date> result =  from  dt in date
where  dt.year == 2007 
select dt;
foreach (Date d in result)
{    Console.WriteLine(d.ToString());}

现在我们再来做一个小的修改

              List<Date> date =Date.CreateDateList();
              IEnumerable<Date> result =  from  dt in date
              where  dt.year == 2007 
              select dt;
              Console.WriteLine("year == 2007");
              foreach (Date d in result)
              {    Console.WriteLine(d.ToString());}
              date[1].year = 2007;
              Console.WriteLine("year == 2007 (take two)");
              foreach (Date d in result)
              {  Console.WriteLine(d.ToString());}

LINQ可以实时的修改查询结果,以应对内存总数据突然改变的情况,这也是LINQ的一大优势

 除此之外,我们还可以通过orderby命令进行排序操作

              List<Date> date =Date.CreateDateList();
              IEnumerable<Date> result =  from  dt in date
              orderby dt.year
              select dt;
              foreach (Date d in result)
              {    Console.WriteLine(d.ToString());}        

我们在orderby语句中加上descending实现降序排序

orderby dt.year descending
原文地址:https://www.cnblogs.com/ljc825/p/4448335.html