zoukankan      html  css  js  c++  java
  • LINQ

    LINQ - Language Integrated Query 语言集成查询

    LINQ 是 C#3.0 的核心。LINQ 是关于查询的,其目的是使用一致的语法和特性,以一种易阅读、可组合的方式,使对多数据源的查询变得简单。

    在这本书《C#7.0 in a Nutshell》中给了linq 的定义:

    1、 Linq is a set of language and framework features for writing structured type-safe queries over local object collections and remote data sources.

    解释一下:Linq是一组语言和框架特性,用于在本地对象集合和远程数据源上编写结构化的类型安全查询。

    2、Linq enables you to query any collection implementing IEnumber<T> ,whether an array, list, or XML DOM,as well as remote Server sources, such as tables in a SQL Server Database .

    linq 可以查询任何实现了 IEnumber<T> 接口的集合,不管它是什么其他的复杂东西。

    3、LINQ offers the benefits of both compile-time type checking and dynamic query composition.

    LINQ提供了编译时类型检查和动态查询组合的优点。

    我们先看一个简单的列子:

    string[] names = {"tom", "Dick", "Harry"}
    IEnumberable<string> filteredNames = System.Linq.Enumerable.Where( names, n=>n.length >=4);
    ​
    foreach(string n in filteredNames)
        Console.WriteLine(n);
    ​
    //*outupt:*//
    Dick
    Harry

    上面的列中names 就是一个序列,where 就是一个操作符。 一个简单的查询包含一个序列和一个操作符。绝大多数的操作符都可以传入一个lambda 表达式,而这个操作符是IEnumerable 的扩展函数。

    n => n.Length >=4 //这就是lambda表达式

    输入参数对应于输入元素,这样的话,输入参数 n 代表每一个 array中的元素。where 操作符 需要lambda 表达式返回一个bool 值,如果是true ,表明这个元素应该属于输出序列。

    public static IEnumerable<TSource> Where<TSource> (this IEnumerable<TSource> source, Func<TSource,bool> predicate) 
    //IEnumerable的扩展函数,在《CLR vai C#》中有详细讲解
       

    上面的例子是linq 的两种写法的其中一种,它叫做 fluent syntax。下面的语法称之为:query syntax

    IEunmerable<string> filteredNames = from n in names where n.Contains("a") select n;

    小结:

    现在我们对 linq 有了一些理解,linq 可以对实现了IEnumber<T>的集合/序列进行操作,输出一个符合条件的序列,linq 通过用 扩展方法+ lambda表达式 实现这个操作,可以查询本地数据集合,和远程数据源(例如数据库)。

  • 相关阅读:
    读书
    Web前端知识体系精简
    让你分分钟理解 JavaScript 闭包
    常用 Git 命令使用教程
    js库写法
    Gitlab的使用
    appium-环境搭建(一)
    Selenium-几种等待方式
    Selenium-免登录的实现
    Selenium-百度登录简单例子
  • 原文地址:https://www.cnblogs.com/mingjie-c/p/11508309.html
Copyright © 2011-2022 走看看