码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-06-15 21:22:50      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:sel   orm   mod   res   border   oid   average   output   clr   

在编译代码时,查询语法必须转换未针对.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 表达式查询和扩展方法查询的区别

标签:sel   orm   mod   res   border   oid   average   output   clr   

原文地址:https://www.cnblogs.com/maanshancss/p/13137640.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!