• Pro LINQ 之—:初识LINQ


    LINQ, bridges the gap and strengthens the connection between relational data and the object-oriented world.

    —Vidya Vrat Agarwal
    《Beginning C# 2008 Database: From Novice to Professional》


    引子

    这是我在阅读《Pro LINQ in C# 2008》时,在书上所做注释的整理与汇总,同样地是作温故知新所用。

    该书全面详尽地讲解了LINQ to Objects、LINQ to XML以及LINQ to SQL的内容,是本不错的书。

    P13 OfType与Cast

    遍历Collection中的项时,尽量使用OfType而不是Cast。这是鉴于Cast操作,会强行对Collection中的每一项进行强制的类型转换,期间可能会导致异常发生。而OfType则不同,它只会返回同类型的项而主动跳过非相同类型的项,从而避免了异常的发生。

    var names = from name in arraylist.Cast<string> select name;
    var names = from name in arraylist.OfType<string> select name;

    P14 Deferred Query

    LINQ在其查询结果第一次被使用时才真正开始执行。因此LINQ作为延迟查询,具有“一次定义、反复使用、总是最新”等特点。

    P23 筛选方法的三种实现方式

    书中使用了一个从整数数组中筛选出奇数的例子,分别采取了如下三种语法方式实现。其本质都是将过滤方法抽象并独立出来,作为一个delegate传递给函数FilterArrayOfInt(),差异仅在于该delegate如何被实现。

    // 使用命名方法
    int[] result = Common.FilterArrayOfInt(nums, Application.IsOdd);
    // 使用匿名代理
    int[] result = Common.FilterArrayOfInt(nums, delegate(int i){return ((i & 1)==1);});
    // 使用lambda表达式
    int[] result = Common.FilterArrayOfInt(nums, (i => ((i & 1)==1)));

    lambda表达式,以=>为分界线,可以简单地理解为左边为参数,右半为方法实现与返回值。

    P24 表达式树

    接口IEnumerable<T> 与IQueryable<T>,是LINQ的核心接口。而序列、接口、方法,则是LINQ的三大要素。

    IEnumerable<T> 的扩展方法总被直接编译为IL代码,而IQueryable<T>的扩展方法为了保证效率和复用,则被编译为lambda表达式。

    // 区别在于两个实现的后半部分
    public static IEnumerable<T> Where<T>(
                    this IEnumerable<T> source,
                    Func<T, bool> predicate);
       
    public static IQueryable<T> Where<T>(
                    this IQueryable<T> source,
                    System.Linq.Expressions.Expression<Func<int, bool>> predicate);

    P25 关键字var

    var 的出现,第一感觉是简化了代码录入,在声明变量时省去了冗长的类型名。细究后发现,var的主要作用在于声明匿名变量,提供泛类型化的访问支持和构造临时性对象更便捷的途径。特别是在LINQ环境下,LINQ语句返回的Collection,经常是临时性的,只作一时之用的。此时通过var构造的临时性对象便显得尤其重要了。

    var unnamedtypeVariable = new {firstArg = 1, secondArg = "Joe"};
    Console.WriteLine(unnamedtypeVariable.firstArg,'.', unnamedtypeVariable.secondArg);
    //---------------------- 
    // 1.Joe

    P30 扩展方法

    问题的提出:static方法只能通过class来调用,从而限制了static方法的使用域。书中提到的情形是要查询若干不同类型的对象数目,于是这个Where方法是通过逐一修改所有的类并提供一个实例级的计数方法,亦或是新建一个静态类然后设计特别一个计数的策略?在SQL查询那样复杂的条件下,无论何种实现都显得极其的繁琐,于是提出了扩展方法的概念,在两种不同类之间自由地建立一个互通的桥梁,实现实例调用类的静态方法。

    扩展方法,就是在不改变被扩展类的前提下,人为地用一个新的类来构造新的方法,实现对原有的被扩展类的功能扩展和改变。

    扩展方法的定义:区别于旧有static方法的地方,在于其参数类型为(this + 被扩展的类型名)。其中this是修饰符。下列代码,即是对string类的一个扩展,为其添加了一个转换为double的扩展方法。

    public static class StringConversions
    {
        public static double ToDouble(this string s)
        { return Double.Parse(s); }
    }

    使用范例如下。其中的"3.1415926"是个string对象,却使用了一个属于StringConversions类的静态方法,即此前定义的扩展方法ToDouble()。

    // "3.1415926" 是一个string的实例
    // ToDouble()是前述StringConversions类的static方法
    double pi = "3.1415926".ToDouble();

    P34 partial方法

    看了半天,感觉就是把方法的实现与方法的声明剥离,类似原来C++的.h与.cpp的关系,把一个类的实现分散到若干个文件里,从而为类的方法提供拆解和替换的捷径。比如选用甲写的某个版本,或者乙的某个版本。关于partial 方法的三个必须:

    1. 类必须是partial class
    2. 方法必须以partial关键字开始
    3. 方法返回类型必须为void

    P38 查询表达式的语法图

    真象极了SQL语句,只是许多地方的顺序完全反了。

    query-expression:
    from-clause query-body
     
    from-clause:
    from typeopt identifier in expression join-clausesopt
     
    join-clauses:
    join-clause
    join-clauses join-clause
     
    join-clause:
    join typeopt identifier in expression on expression equals
    expression
    join typeopt identifier in expression on expression equals
    expression into identifier
     
    query-body:
    from-let-where-clausesopt orderby-clauseopt select-or-group-clause
    query-continuationopt
     
    from-let-where-clauses:
    from-let-where-clause
    from-let-where-clauses from-let-where-clause
     
    from-let-where-clause:
    from-clause
    let-clause
    where-clause
     
    let-clause:
    let identifier = expression
     
    where-clause:
    where boolean-expression
     
    orderby-clause:
    orderby orderings
     
    orderings:
    ordering
    orderings , ordering
     
    ordering:
    expression ordering-directionopt
     
    ordering-direction:
    ascending
    descending
     
    select-or-group-clause:
    select-clause
    group-clause
     
    select-clause:
    select expression
     
    group-clause:
    group expression by expression
     
    query-continuation:
    into identifier join-clausesopt query-body

    P41 linq语句的转译

    作者使用了一张转义符号表,用单个字母替代linq语句中的某个语法元素,并且建议按逆序阅读和理解这个转译的过程。了解编译LINQ的过程,是熟悉LINQ语法的进阶手段。

    在这个过程中,他举了许多典型的例子,然后分别用“类sql”和“扩展方法”的语法形式表达。

    下列示例中,注释部分为等价的SQL查询语句与个人的注解。

    from c in customers
    group c by c.Country into g
    select new {Country = g.Key, CustCount = g.Count()}
     
    // select Country, count(Coustomerid) from Customers group by Country
    from c in customers
    join o in orders
    on c.customerid equals o.customerid
    select new {c.contactname, o.orderdate, o.freight}
     
    // select c.contactname, o.orderdate, o.freight
    // from customers as c, orders as o
    // where c.customerid = o.customerid
    from c in customers
    join o in orders
    on c.customerid equals o.customerid
    into co
    select new {c.contactname, summery = co.Sum(o => o.freight)}
     
    // 形成1:M的关系,其中1是customers中的一项,M是orders中所有customerid与之相匹配的记录。
    // 把 join ... on ... into ...作为一个整体看待,即容易理解了。
     
    // select c.contactname, sum(o.freight) as summery
    // from customers as c, orders as o
    // group by o.contactname
     
    // select c.contactname,
    //       (select sum(o.freight) from orders as o
    //       where c.customerid = o.customerid) as sumerry
    // from customers as c

    Pro LINQ 之二:LINQ to Objects

  • 相关阅读:
    用了这款docker监控平台,再也不用记一大堆命令了,真香!
    自动化脚本如何切换环境?Pytest这些功能你必须要掌握
    5年高级测试员,还不会用Pytest+Allure实现自动化用例失败截图
    guava包Range操作
    guava包EventBus
    guava集合类(一)
    Neo4j基本入门
    在springboot中使用jdbcTemplate(6)
    guava包Strings工具类
    ASM介绍及简易教程(转)
  • 原文地址:https://www.cnblogs.com/Abbey/p/2104795.html
Copyright © 2020-2023  润新知