数据库中八大字句


八大子句

LINQ查询子句概述

    1.查询(Query)是一组指令,这些指令可以从一个或多个给定的数据源中检索数据,并指定检索结果的数据类型和表现形式。

    2.查询表达式是一种查询语法表示的表达式,由一组用类似于SQL的声明性语法编写的子句组成。

    3.每一个字句可以包含一个或多个C#表达式,而这些表达式本身又可能是查询表达式或包含查询表达式。

    4.查询表达式和其他表达式一样,可以用在C#表达式有效的任何上下文中。

子句说明

  •     LINQ查询表达式必须以from子句开头,并且必须以select或group子句结束。
  •     在第一个from子句和最后一个select或group子句之间,查询表达式可以包含一个或多个where、orderby、group、           join、let子句,甚至from子句。
  •     另外,join和group子句还可以使用into子句指定临时标识符号

数据库查询子句: 

   1.  from...in子句:指定查询操作的数据源和范围变量

        在 LINQ 查询中,第一步是指定数据源。像在大多数编程语言中一样,在 C# 中,必须先声明变量,才能使用它。在 LINQ 查询中,最先使用 from 子句的目的是引入数据源 ( customers) 和范围变量 ( cust)。

[csharp]  view plain  copy
  1. //queryAllCustomers is an IEnumerable<Customer>  
  2.            var queryAllCustomers = <span style="color:#3366ff;">from</span> cust <span style="color:#3366ff;">in</span> customers  
  3.                        select cust;  

2.   select子句:指定查询结果的类型和表现形式

      在查询表达式中, select 子句可以指定将在执行查询时产生的值的类型。 该子句的结果将基于前面所有子句的计算结果以及 select 子句本身中的所有表达式。 查询表达式必须以 select 子句或 group 子句结束。 

[csharp]  view plain  copy
  1. class SelectSample1  
  2. {     
  3.     static void Main()  
  4.     {             
  5.         //Create the data source  
  6.         List<int> Scores = new List<int>() { 97, 92, 81, 60 };  
  7.   
  8.         // Create the query.  
  9.         IEnumerable<int> queryHighScores =  
  10.             from score in Scores  
  11.             where score > 80  
  12.             <span style="color:#3366ff;">select</span> score;  
  13.   
  14.         // Execute the query.  
  15.         foreach (int i in queryHighScores)  
  16.         {  
  17.             Console.Write(i + " ");  
  18.         }              
  19.     }  
  20. }  
  21. //Output: 97 92 81  


 3.   where子句:筛选元素的逻辑条件,一般由逻辑元算符组成

       where 子句用在查询表达式中,用于指定将在查询表达式中返回数据源中的哪些元素。 它将一个布尔条件(“谓词”)应用于每个源元素(由范围变量引用),并返回满足指定条件的元素。一个查询表达式可以包含多个 where 子句,一个子句可以包含多个谓词子表达式。

[csharp]  view plain  copy
  1. class WhereSample  
  2. {  
  3.     static void Main()  
  4.     {     
  5.         // Simple data source. Arrays support IEnumerable<T>.  
  6.         int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };  
  7.   
  8.         // Simple query with one predicate in where clause.  
  9.         var queryLowNums =  
  10.             from num in numbers  
  11.             <span style="color:#3366ff;">where</span> num < 5  
  12.             select num;  
  13.   
  14.         // Execute the query.  
  15.         foreach (var s in queryLowNums)  
  16.         {  
  17.             Console.Write(s.ToString() + " ");  
  18.         }  
  19.     }  
  20. }  
  21. //Output: 4 1 3 2 0  
[csharp]  view plain  copy
  1.   

 4.    group...by子句:对查询进行分组

            使用 group 子句,您可以按指定的键分组结果。

       

[csharp]  view plain  copy
  1. // queryCustomersByCity is an IEnumerable<IGrouping<string, Customer>>  
  2.          var queryCustomersByCity =  
  3.           from cust in customers  
  4.           <span style="color:#3366ff;">group</span> cust <span style="color:#3366ff;">by</span> cust.City;  
  5.   
  6.   
  7.       // customerGroup is an IGrouping<string, Customer>  
  8.           foreach (var customerGroup in queryCustomersByCity)  
  9.           {  
  10.               Console.WriteLine(customerGroup.Key);  
  11.               foreach (Customer customer in customerGroup)  
  12.           {  
  13.               Console.WriteLine("    {0}", customer.Name);  
  14.           }  
  15.       }  

    在使用 group 子句结束查询时,结果采用列表的列表形式。 列表中的每个元素是一个具有 Key 成员及根据该键分组的元素列表的对象。 在循环访问生成组序列的查询时,您必须使用嵌套的 foreach 循环。 外部循环用于循环访问每个组,内部循环用于循环访问每个组的成员。

5.     orderby子句:对查询结果进行排序,可以为“升序”或“降序”

       在查询表达式中, orderby 子句可使返回的序列或子序列(组)按升序或降序排序。 可以指定多个键,以便执行一个或多个次要排序操作。排序是由针对元素类型的默认比较器执行的。默认排序顺序为升序。

[csharp]  view plain  copy
  1. class OrderbySample1  
  2. {  
  3.     static void Main()  
  4.     {              
  5.         // Create a delicious data source.  
  6.         string[] fruits = { "cherry""apple""blueberry" };  
  7.   
  8.         // Query for ascending sort.  
  9.         IEnumerable<string> sortAscendingQuery =  
  10.             from fruit in fruits  
  11.             orderby fruit //"ascending" is default  
  12.             select fruit;  
  13.   
  14.         // Query for descending sort.  
  15.         IEnumerable<string> sortDescendingQuery =  
  16.             from w in fruits  
  17.             orderby w descending  
  18.             select w;              
  19.   
  20.         // Execute the query.  
  21.         Console.WriteLine("Ascending:");  
  22.         foreach (string s in sortAscendingQuery)  
  23.         {  
  24.             Console.WriteLine(s);  
  25.         }  
  26.   
  27.         // Execute the query.  
  28.         Console.WriteLine(Environment.NewLine + "Descending:");  
  29.         foreach (string s in sortDescendingQuery)  
  30.         {  
  31.             Console.WriteLine(s);  
  32.         }  
  33.   
  34.         // Keep the console window open in debug mode.  
  35.         Console.WriteLine("Press any key to exit.");  
  36.         Console.ReadKey();  
  37.     }  
  38. }  
  39. /* Output: 
  40. Ascending: 
  41. apple 
  42. blueberry 
  43. cherry 
  44.  
  45. Descending: 
  46. cherry 
  47. blueberry 
  48. apple 
  49. */  

  6.    join子句:连接多个查询操作的数据源

       

        使用 join 子句可以将来自不同源序列并且在对象模型中没有直接关系的元素相关联。 唯一的要求是每个源中的元素需要共享某个可以进行比较以判断是否相等的值。例如,食品经销商可能具有某种产品的供应商列表以及买主列表。例如,可以使用 join 子句创建该产品同一指定地区供应商和买主的列表。

        join 子句接受两个源序列作为输入。 每个序列中的元素都必须是可以与另一个序列中的相应属性进行比较的属性,或者包含一个这样的属性。join 子句使用特殊的 equals 关键字比较指定的键是否相等。 join 子句执行的所有联接都是同等联接。 join 子句的输出形式取决于所执行的联接的具体类型。 以下是三种最常见的联接类型:

  • 内部联接

[csharp]  view plain  copy
  1. var innerJoinQuery =  
  2.     from category in categories  
  3.     <span style="color:#3366ff;">join</span> prod in products on category.ID equals prod.CategoryID  
  4.     select new { ProductName = prod.Name, Category = category.Name }; //produces flat sequence  

  • 分组联接

[csharp]  view plain  copy
  1. var innerGroupJoinQuery =  
  2.     from category in categories  
  3.     <span style="color:#3366ff;">join </span>prod in products on category.ID equals prod.CategoryID into prodGroup  
  4.     select new { CategoryName = category.Name, Products = prodGroup };  

  • 左外部联接

[csharp]  view plain  copy
  1. var leftOuterJoinQuery =  
  2.     from category in categories  
  3.     join prod in products on category.ID equals prod.CategoryID into prodGroup  
  4.     from item in prodGroup.DefaultIfEmpty(new Product{Name = String.Empty, CategoryID = 0})  
  5.         select new { CatName = category.Name, ProdName = item.Name };  
[csharp]  view plain  copy
  1.   

   7.    let子句:引入用于存储查询表达式中的子表达式结果的范围变量

        在查询表达式中,存储子表达式的结果有时很有用,这样可以在随后的子句中使用。可以使用 let 关键字完成这一工作,该关键字可以创建一个新的范围变量,并且用您提供的表达式的结果初始化该变量。 一旦用值初始化了该范围变量,它就不能用于存储其他值。但如果该范围变量存储的是可查询的类型,则可以对其进行查询。

[csharp]  view plain  copy
  1. class LetSample1  
  2. {  
  3.     static void Main()  
  4.     {  
  5.         string[] strings =   
  6.         {  
  7.             "A penny saved is a penny earned.",  
  8.             "The early bird catches the worm.",  
  9.             "The pen is mightier than the sword."   
  10.         };  
  11.   
  12.         // Split the sentence into an array of words  
  13.         // and select those whose first letter is a vowel.  
  14.         var earlyBirdQuery =  
  15.             from sentence in strings  
  16.             let words = sentence.Split(' ')  
  17.             from word in words  
  18.             let w = word.ToLower()  
  19.             where w[0] == 'a' || w[0] == 'e'  
  20.                 || w[0] == 'i' || w[0] == 'o'  
  21.                 || w[0] == 'u'  
  22.             select word;  
  23.   
  24.         // Execute the query.  
  25.         foreach (var v in earlyBirdQuery)  
  26.         {  
  27.             Console.WriteLine("\"{0}\" starts with a vowel", v);  
  28.         }  
  29.   
  30.         // Keep the console window open in debug mode.  
  31.         Console.WriteLine("Press any key to exit.");  
  32.         Console.ReadKey();  
  33.     }  
  34. }  
  35. /* Output: 
  36.     "A" starts with a vowel 
  37.     "is" starts with a vowel 
  38.     "a" starts with a vowel 
  39.     "earned." starts with a vowel 
  40.     "early" starts with a vowel 
  41.     "is" starts with a vowel 
  42. */  


   8.    into子句:提供一个临时标示符,充当对join、group或select子句的结果

        引用组操作的结果,可以使用 into 关键字来创建可进一步查询的标识符。 下面的查询只返回那些包含两个以上的客户的组:

[csharp]  view plain  copy
  1. // custQuery is an IEnumerable<IGrouping<string, Customer>>  
  2.        var custQuery =  
  3.        from cust in customers  
  4.        <span style="color:#3366ff;">group</span> cust <span style="color:#3366ff;">by</span> cust.City <span style="color:#3366ff;">into </span>custGroup  
  5.        where custGroup.Count() > 2  
  6.        orderby custGroup.Key  
  7.        select custGroup;  

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值