2.1 表达式查询和扩展方法查询的区别

Posted maanshancss

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2.1 表达式查询和扩展方法查询的区别相关的知识,希望对你有一定的参考价值。

在编译代码时,查询语法必须转换未针对.net CLR的方法调用。这些方法调用会调用标准查询运算符(名称未Where、Select、GroupBy、Join、Max和Average等),也就是表达式查询最终会变成扩展方法查询,只不过表达式查询看起来更明了,更加符合SQL语句的习惯;我习惯使用SQL语句,所以我一般习惯用表达式查询;

表达式查询

from
<range variable>
in
<IEnumerable<T> or IQueryable<T> Collection>


<Standard Query Operators>
<lambda expression>


<select or groupBy operator>
<result formation>
//以from开头,以select结尾;

// string collection
IList<string> stringList = new List<string>() {
    "C# Tutorials",
    "VB.NET Tutorials",
    "Learn C++",
    "MVC Tutorials" ,
    "Java"
};

// LINQ Query Syntax
var result = from s in stringList
            where s.Contains("Tutorials")
            select s;

扩展方法查询

语法: 扩展方法 + Lambda Expression

//例子一
// string collection
IList<string> stringList = new List<string>() {
    "C# Tutorials",
    "VB.NET Tutorials",
    "Learn C++",
    "MVC Tutorials" ,
    "Java"
};

// LINQ Query Syntax
var result = stringList.Where(s => s.Contains("Tutorials"));

//例子二
// Student collection
IList<Student> studentList = new List<Student>() {
        new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
        new Student() { StudentID = 2, StudentName = "Moin",  Age = 21 } ,
        new Student() { StudentID = 3, StudentName = "Bill",  Age = 18 } ,
        new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
        new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
    };

// LINQ Method Syntax to find out teenager students
var teenAgerStudents = studentList.Where(s => s.Age > 12 && s.Age < 20)
                                  .ToList<Student>();
class QueryVMethodSyntax
{
    static void Main()
    {
        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(System.Environment.NewLine);
        foreach (int i in numQuery2)
        {
            Console.Write(i + " ");
        }

        // Keep the console open in debug mode.
        Console.WriteLine(System.Environment.NewLine);
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
}
/*
    Output:
    6 8 10 12
    6 8 10 12
*/

以上是关于2.1 表达式查询和扩展方法查询的区别的主要内容,如果未能解决你的问题,请参考以下文章

编写高质量代码改善C#程序的157个建议——建议27:在查询中使用Lambda表达式

having和group by的区别?

找不到使用'[bracket]'和'查询查询属性之间的区别。点'符号

4.复杂一点的查询

C#图解教程 第十九章 LINQ

linq