zoukankan      html  css  js  c++  java
  • 光脚丫学LINQ(013):LINQ查询语法与方法语法

    视频演示:http://u.115.com/file/f2f1e1a2f4

    通过使用 C# 3.0 中引入的声明性查询语法,介绍性 LINQ 文档中的多数查询都被编写为查询表达式。但是,.NET 公共语言运行时 (CLR) 本身并不具有查询语法的概念。因此,在编译时,查询表达式会转换为 CLR 确实了解的内容:方法调用。这些方法称为“标准查询运算符”,它们具有如下名称:Where、Select、GroupBy、Join、Max、Average 等。 可以通过使用方法语法而非查询语法来直接调用这些方法。
    通常我们建议使用查询语法,因为它通常更简单、更易读;但是方法语法和查询语法之间并无语义上的区别。此外,一些查询(如检索匹配指定条件的元素数的那些查询或检索具有源序列中的最大值的元素的查询)只能表示为方法调用。System.Linq 命名空间中的标准查询运算符的参考文档通常使用方法语法。因此,即使在开始编写 LINQ 查询时,熟悉如何在查询和查询表达式本身中使用方法语法也非常有用。
      
    标准查询运算符扩展方法
    下面的示例演示简单的查询表达式和编写为基于方法的查询的语义上等效的查询。

    static void Main(string[] args)   
    {   
        int[] Numbers = { 5, 10, 8, 3, 6, 12 };   
      
        // Query syntax:   
        IEnumerable<int> NumQuery1 =   
            from num in Numbers   
            where num % 2 == 0   
            orderby num   
            select num;   
      
        // Method syntax:   
        IEnumerable<int> NumQuery2 =   
            Numbers.Where(num => num % 2 == 0).OrderBy(n => n);   
      
        foreach (int i in NumQuery1)   
        {   
            Console.Write(i + " ");   
        }   
        Console.WriteLine(Environment.NewLine);   
        foreach (int i in NumQuery2)   
        {   
            Console.Write(i + " ");   
        }   
      
        // Keep the console open in debug mode.   
        Console.WriteLine(Environment.NewLine);   
        Console.WriteLine("Press any key to exit");   
        Console.ReadKey();   
      
    }  
    static void Main(string[] args)
    {
        int[] Numbers = { 5, 10, 8, 3, 6, 12 };
    
        // Query syntax:
        IEnumerable<int> NumQuery1 =
            from num in Numbers
            where num % 2 == 0
            orderby num
            select num;
    
        // Method syntax:
        IEnumerable<int> NumQuery2 =
            Numbers.Where(num => num % 2 == 0).OrderBy(n => n);
    
        foreach (int i in NumQuery1)
        {
            Console.Write(i + " ");
        }
        Console.WriteLine(Environment.NewLine);
        foreach (int i in NumQuery2)
        {
            Console.Write(i + " ");
        }
    
        // Keep the console open in debug mode.
        Console.WriteLine(Environment.NewLine);
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    
    } 
    


    两个示例的输出是相同的。您可以看到两种形式的查询变量的类型是相同的:IEnumerable<T>。

  • 相关阅读:
    caffe常用层: batchNorm层和scale层
    简述configure、pkg-config、pkg_config_path三者的关系
    python删除list中元素的三种方法
    Leetcode 872. Leaf-Similar Trees
    Leetcode 508. Most Frequent Subtree Sum
    Leetcode 572. Subtree of Another Tree
    Leetcode 894. All Possible Full Binary Trees
    Leetcode 814. Binary Tree Pruning
    Leetcode 557. Reverse Words in a String III
    python 多维list声明时的小问题
  • 原文地址:https://www.cnblogs.com/GJYSK/p/1864245.html
Copyright © 2011-2022 走看看