C#中Linq查詢基本操作


摘要:本文介紹Linq查詢基本操作(查詢關鍵字)

- from 子句

- where 子句

- select子句

- group 子句

- into 子句

- orderby 子句

- join 子句

- let 子句

- 復合from子句

- 在某些情況下,源序列中的每個元素本身可能是序列(集合),也可能包含序列

- 用語訪問單個數據庫中的內部集合

- 使用多個from字句執行連接

- 可以包含多個可從獨立數據源生成補充查詢的from字句

復合(顧名思義就是有多from的字句)實例:

class Program
{
    static void Main(string[] args)
    {
        List<Student> students = new List<Student>         
        {            
            new Student 
            {
                LastName="xiaogui",Scores=new List<int>{97,42,91,60}},
                new Student
                {
                    LastName="xiaozhan",Scores=new List<int>{50,92,81,60}},   
                    new Student 
                    {
                        LastName="xiaolan",Scores=new List<int>{32,32,81,90}},
                        new Student 
                        {
                            LastName="xiaowan",Scores=new List<int>{92,22,81,60}},         
        };
        var query = from stuent in students
                    from score in stuent.Scores
                    where score > 90
                    select new
                    {
                        Last = stuent.LastName,
                        score
                    };
        foreach (var student in query)//大於90分的顯示出來        
        {
            Console.WriteLine("{0} Score:{1}", student.Last, student.score);
        }
        Console.ReadLine();
    }
}
public class Student 
{ 
    public string LastName { get; set; } 
    public List<int> Scores { get; set; }
}
public class Employee
{
    public string First { get; set; }
    public string Last { get; set; }
    public int ID { get; set; }
}

執行結果: xiaogui Score:97

              xiaogui Score:91

              xiaozhan Score:92

              xiaowan Score:92

let 關鍵字(使用let字句擴展范圍變量)

- 創建一個可以查詢自身的可枚舉類型

- 使查詢只能對范圍變量word調用一次ToLower。

如果不使用let,則必須在where字句的每個謂詞中調用ToLower

例:把每個單詞開頭包含a或者e的找出來

using System;
using System.Linq;

public class Test
{
    static void Main(string[] args)
    {
        string[] strings = { "A penny saved is a penny earned.", "The aaxly sdj", "the pa is no" };

        var query = from sentence in strings
                    let words = sentence.Split(' ')//用空格分割成數組                
                    from word in words
                    let w = word.ToLower()//把每個字母小寫        
                    where w[0] == 'a' || w[0] == 'e'
                    select word;

        foreach (var s in query)
        {
            Console.WriteLine(s);
        }
        Console.ReadLine();
    }
}

where 關鍵字 (篩選)

- 一個查詢表達式可以包含多個where字句

:(把包含a的找出來)

using System;
using System.Linq;

public class Test
{
    static void Main(string[] args)
    {
        string[] str = { "a", "b", "c" };

        var query = from s in str
                    where s == "a"
                    select s;

        foreach (var s in query)
        {
            Console.WriteLine(s);
        }
        Console.ReadLine();
    }
}

orderby 關鍵字 (排序)

- 在查詢表達式中,orderby字句可以使返回的序列(組)按升序或降序。

- 可以指定多個鍵,以便執行一個或多個次要排序操作

- 默認排序順序為升序

- 編譯時,orderby字句被轉換為對OrderBy方法的調用。orderby字句中的多個鍵被轉換為ThenBy方法調用

descending 降序

ascending 升序

例1:升序

using System;
using System.Linq;

public class Test
{
    static void Main(string[] args)
    {
        string[] str = { "a", "b", "c" };
        var query = from s in str
                    orderby s ascending
                    select s;
    }
}

結果為: a b c

例2:降序

using System;
using System.Linq;

public class Test
{
    static void Main(string[] args)
    {
        string[] str = { "a", "b", "c" }; 
        var query = from s in str 
                    orderby s descending 
                    select s;
    }
}

結果為: c b a

group 關鍵字 (分組)

- group 字句返回一個IGrouping(TKey,Telement)對象序列 

- 編譯時,group子句被轉換為對GroupBy方法的調用

(LINQ查詢表達式可以以select或者Group結束) (如果想要對每個組執行附加查詢操作,則可以使用into上下文關鍵字指定一個臨時標識符,使用into時,必須繼續編寫該查詢,並最終用一個select語句或另一 個group子句結束該查詢)

例:

using System;
using System.Linq;

public class Test
{
    static void Main(string[] args)
    {
        string[] str = { "aa", "bb", "cc", "dd" };
        var query = from s in str
                    group s by s[0]
                        into p
                        where p.Key == 'a' || p.Key == 'b' || p.Key == 'c'
                        orderby p.Key descending
                        select p.Key;

        foreach (var s in query)
        {
            Console.WriteLine(s);
        }
        Console.ReadLine();
    }
}

結果為: c b a

說明: group s by s[0] into p 意思是針對范圍變量s用“s[0]”分組,本例中是用第一個字母分組

join 關鍵字 (聯接)

- 使用join 子句可以將來自不同源序列並且在對象模型中沒有直接關系的元素相關聯

- 唯一的要求是每個源中的元素需要共享某個可以進行比較以判斷是否相等的值

- join字句使用特殊的equals關鍵字比較指定的鍵是否相等

三中常見的連接類型

- 內部聯接

- 分組聯接

- 左外部聯接

1.內部聯接

   var query = from a
                        in str
                    join b in str2 on a.id equals b.id
                    select new { Aname = a.name, Bname = b.name };

2.分組聯接:(into 可以將join暫存起來)

    var query =  from a in str 
                  join b in str2 on a.id equals b.id 
                  into c
                  select new {Aname=a.name,Cs=c}

3.左外部聯接

- 在左外部聯接中,將返回左則源序列中所有元素,即使它們在右則序列中沒有匹配的元素也是如此。

- 若要在LINQ中執行左外部聯接,請將DefaultifEmpty方法與分組聯接結合起來,以指定要在某個左則元素不具有匹配元素時產生的默認右則元素。可以使用null作為任何引

用類型的默認值,也可以指定用戶定義的默認類型。

 var query =  from category 
                  in categories 
              join prod in products on category.id equals prod.CategoryID 
              into prodGroup 
              from item prodGroup.defaultifEmpty(
                  new Product{Name=string.empty,CategoryID=0}) 
        select new {CatName=category.Name,ProdName=item.Name}

equalse 運算符

- join 子句執行同等聯接。換句話說,只能基於兩個鍵之間的相等關系進行匹配

- 為了表明所有聯接都是相等聯接,join子句使用equals關鍵字而不是==運算符

復合鍵

- 使用復合鍵可以測試多個值是否相等

select 關鍵字 選擇


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM