刚刚接触的LINQ

科普一下:

语言集成查询(Language INtegrated Query,LINQ)

是一项微软技术,新增一种自然查询的SQL语法到.NET Framework的编程语言中,可支持Visual Basic .NET以及C#语言。

LINQ定义了大约40个查询操作符,如select、from、in、where以及order by(C#中)。

使用这些操作符可以编写查询语句。不过,这些查询还可以基于很多类型的数据,每个数据类型都需要一个单独的LINQ类型。

基础语法:

  • LINQ的关键词:from, select, in, where, group by, orderby, …
  • LINQ的注意点:必须以select或者是group by 结束。
  • LINQ的写法:

1)from 临时变量 in 实现IEnumerable<T>接口的对象

where条件表达式

[orderby条件]

[group by 条件]

select 临时变量中被查询的值

2) 实现IEnumerable接口的对象.LINQ方法名(lambda表达式)。如:

string input = "hellow world";

int count = input.Count(w=>w == 'o'); //查询字母o出现的次数

能够使用LINQ的对象需要实现IEnumerable<T>接口。并且LINQ的查询表达式是在一次创建对象时才被编译的。

  • LINQ的全称:Language-Integrated Query
  • 命名空间:System.Linq;

  注意:Linq是在.NET Framework 3.5 中出现的技术,所以在创建新项目的时候必须要选3.5或者更高版本,否则无法使用。

  选择3.5或更高版本的.NET Framework之后,创建的新项目中会自动包含System.Linq的命名空间。

接着看代码实现:

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

namespace LINQ
{
    public class Category
    {
        public int Age { get; set; }
        public string Prase { get; set; }
    }
    public class Program
    {
        static void Main(string[] args)
        {
            //对数据集合的操作
            List<string> names = new List<string> { "Tom", "Jack", "Jim", "Jackson", "Key", "Kitty" };
            var nameJ = from n in names where n.StartsWith("J") orderby n select n;
            foreach (var name in nameJ)
            {
                Console.WriteLine(name);
            }

            Console.WriteLine("-------------------------");

            names.Add("Jack1");
            names.Add("Jack2");
            names.Add("Jack3");
            foreach (string name in nameJ)
            {
                Console.WriteLine(name);
            }
            Console.WriteLine("-------------------------");
            
            List<Category> cs = new List<Category>() { 
                new Category{Age=22,Prase="13期"},new Category{Age=22,Prase="12期"},new Category{Age=22,Prase="14期"},
            new Category{Age=23,Prase="14期"},new Category{Age=20,Prase="13期"},new Category{Age=24,Prase="14期"},
            new Category{Age=25,Prase="14期"},new Category{Age=23,Prase="13期"},new Category{Age=25,Prase="14期"}
            };
            var s = (from s1 in cs where s1.Age > 21 && s1.Prase == "14期" orderby s1.Age descending select s1).Take(3);
            foreach (var c1 in s)
            {
                Console.WriteLine(c1.Age + " " + c1.Prase);
            }

            Console.WriteLine("-------------------------");

            var ss = from s1 in cs
                    group s1 by s1.Prase into c
                    orderby c.Count() descending, c.Key
                    where c.Count() >= 2
                    select c.Key + c.Count();
            foreach (var s1 in ss)
            {
                Console.WriteLine(s1);
            }

            Console.WriteLine("-------------------------");

            object[] data = { "hello",33,"what",36,"fine",39,"thanks"};
            var str = data.OfType<string>();
            foreach (var a in str)
            {
                Console.WriteLine(a);
            }
            Console.ReadKey();
        }
    }
}

  

上述代码除了LINQ查询语法外,其他都是我们所熟悉的语法,而LINQ查询语法跟SQL查询语法很相似,除了先后顺序。

  Q:为何 LINQ 查询语法是以 from 关键字开头的,而不是以 select 关键字开头的?select 开头这种写法跟SQL的写法更接近,更易懂呀?

  A:简单来说,为了IDE的智能感知(Intelisence)这个功能,select 关键字放在后面了。

  其中的 into 关键字表示 将前一个查询的结果视为后续查询的生成器,这里是跟 group by 一起使用的。

  LINQ中的Group by不要跟 SQL 中的Group by 混淆,SQL由于是二维结构,Group by 的一些逻辑受二维结构的约束,无法像 LINQ 中的Group by 这么灵活。

  事实上,LINQ的查询语法存在以下两种形式:

  查询方法方式:(Methord Syntax)

  主要利用System.Linq.Enumerable类中定义的扩展方法和Lambda表达式方式进行查询

     参考文档:Lambda 表达式(C# 编程指南):https://msdn.microsoft.com/zh-cn/library/bb397687.aspx

  查询语句方式:(Query Syntax)一种更接近SQL语法的查询方式,可读性更好。

使用优点:

  1、无需复杂学习过程即可上手

  2、编写更少代码即可创建完整应用。

  3、更快开发错误更少的应用程序

  4、无需求助奇怪的编程技巧就可合并数据源

  5、让新开发者开发效率更高。

  6、任何对象或数据源都可以定制实现Linq 适配器,为数据交互带来真正方便。

函数支持:

支持以下公共语言运行时 (CLR) 方法和属性,因为它们可以在查询表达式中进行转换以包含在OData服务的请求 URI 中:

String成员支持的 OData 函数
  Concat   string,concat(string,p0,string,p1)
  Contains   bool,substringof(string,p0,string,p1)
  EndsWith   bool,endswith(string,p0,string,p1)
  IndexOf   int,indexof(string,p0,string,p1)
  Length   int,length(string,p0)
  Replace   string,replace(string,p0,string,find,string,replace)
  Substring   string,substring(string,p0,int,pos)
  Substring   string,substring(string,p0,int,pos,int,length)
  ToLower   string,tolower(string,p0)
  ToUpper   string,toupper(string,p0)
  Trim   string,trim(string,p0)
DateTime成员1支持的 OData 函数
  Day   int,day(DateTime,p0)
  Hour   int,hour(DateTime,p0)
  Minute   int,minute(DateTime,p0)
  Month   int,month(DateTime,p0)
  Second   int,second(DateTime,p0)
  Year   int,year(DateTime,p0)

  1也支持Visual Basic中等效的Microsoft.VisualBasic.DateAndTime的日期和时间属性以及DatePart方法。

Math成员支持的 OData 函数
  Ceiling   decimal,ceiling(decimal,p0)
  Ceiling   double,ceiling(double,p0)
  Floor   decimal,floor(decimal,p0)
  Floor   double,floor(double,p0)
  Round   decimal,round(decimal,p0)
  Round   double,round(double,p0)
Expression成员支持的 OData 函数
  TypeIs   bool,isof(type,p0)

  客户端或许还可以在客户端上计算其他 CLR 函数。对于无法在客户端上计算以及无法转换为有效请求URI以便在服务器上计算的任何表达式,将引发 NotSupportedException

参考文档:在 C# 中编写查询 (LINQ):https://msdn.microsoft.com/zh-cn/library/bb397900(v=VS.90).aspx?lc=2052

原文地址:https://www.cnblogs.com/D-E-S-I-R-E/p/4573807.html