程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#應用LINQ查詢表達式的根本子句總結

C#應用LINQ查詢表達式的根本子句總結

編輯:C#入門知識

C#應用LINQ查詢表達式的根本子句總結。本站提示廣大學習愛好者:(C#應用LINQ查詢表達式的根本子句總結)文章只能為提供參考,不一定能成為您想要的結果。以下是C#應用LINQ查詢表達式的根本子句總結正文


LINQ查詢表達式的根本語法很輕易控制,它應用C#罕見的說話結構,從外不雅上看,和我們經常使用的SQL相似,而且查詢表達式中的變量可以用匿名類型,所以在許多情形下,不須要指定變量類型便可以構建LINQ表達式。

LINQ的數據源可所以數據庫對象或是XML流等,也能夠使完成了IEnumerable或許泛型IEnumberable<T>接口的聚集對象。

LINQ的根本語法包括以下的8個高低文症結字,這些症結字和詳細的解釋以下:
症結字

解釋
from 指定規模變量和數據源 where 依據bool表達式從數據源中挑選數據 select 指定查詢成果中的元素所具有的類型或表示情勢 group 對查詢成果依照鍵值停止分組(IGrouping<TKey,TElement>) into 供給一個標識符,它可以充任對join、group或select子句成果的援用 orderby 對查詢出的元素停止排序(ascending/descending) join 依照兩個指定婚配前提來Equals銜接兩個數據源 let 發生一個用於存儲查詢表達式中的子表達式查詢成果的規模變量
上面依此總結這8個症結字的經常使用查詢語句寫法。

1.from子句
假如要寫一個LINQ表達式,就必需是以from子句開首。小我認為from子句中須要留意的處所就是多個from子句的書寫。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace LINQ
{
  /// <summary>
  /// LINQ,重點是感悟from子句中的查詢變量的靈巧
  /// </summary>
  class Program
  {
    static void Main(string[] args)
    {
      //1單個form子句
      string[] values = { "LINQ進修","LINQ根本語句","from子句","單個from子句"};
      var value = from v in values
            where v.IndexOf("LINQ") > -1
            select new { v, v.Length };
      foreach (var n in value)
      {
        Console.WriteLine("{0},{1}",n.v,n.Length );
      }
      Console.ReadKey(false);
      //2應用LINQ查詢ArrayList
      ArrayList gList = new ArrayList();
      gList.Add(new GustInfo { Name="DebugLZQ", Age=26, Tel="88888888"});
      gList.Add(new GustInfo { Name="博客園",Age=6, Tel ="666666"});
      gList.Add(new GustInfo { Name = "M&MSoft", Age =9, Tel = "55555" });

      var query = from GustInfo gust in gList
            where gust.Age > 9
            select gust;//規模變量gust制訂了數據類型
      foreach (GustInfo g in query)
      {
        Console.WriteLine("{0} 年紀:{1} 德律風:{2}",g.Name,g.Age,g.Tel );
      }
      Console.ReadKey(false);
      //3復合from子句
      List<GustInfo2> gList2 = new List<GustInfo2>() 
      {
        new GustInfo2{ Name="DebugLZQ",Age=26,TelTable=new List<string>(){"8888888","138******"}},
        new GustInfo2{ Name="博客園",Age=6,TelTable =new List<string>(){"666666","138******"}},
        new GustInfo2{ Name="M&MSoft",Age=9,TelTable=new List<string>(){"55555","138******"}}
      };

      //gust、tel都是查詢變量,感化域為以後查詢語句!!!
      var query2 = from gust in gList2
             from tel in gust.TelTable 
             where tel.IndexOf("5555") > -1
             select gust;
      foreach (var g in query2)
      {
        Console.WriteLine("{0} 年紀{1}",g.Name,g.Age );
        foreach (var t in g.TelTable)
        {
          Console.WriteLine("德律風:{0}",t);
        }
      }

      Console.ReadKey(false);

      //4多個from子句
      var query3 = from GustInfo gust in gList
             where gust.Age > 6
             from GustInfo2 gust2 in gList2
             where gust2.Age> 9
             select new { gust, gust2 };//查詢成果定制
      foreach (var g in query3)
      {
        Console.WriteLine("{0} {1}", g.gust.Name, g.gust2.Name);
      }

      Console.ReadKey(false);
    }
  }
}

法式的運轉成果以下:

201637153703558.png (677×442)

法式中羅列了from子句的用法示例,留意復合from子句和多個from子句的書寫,同時須要懂得規模變量和數據源變量這兩個概念。

 2.where子句
where子句,它是LINQ表達式的元素挑選機制,除開端和停止的地位,它簡直可以湧現在LINQ表達式的隨意率性地位上。

在一個LINQ表達式中,可以有where子句,也能夠沒有;可以有一個,也能夠有多個;多個where子句之間的邏輯關系相當於邏輯“與”,每一個where子句可以包括1個或多個bool邏輯表達式,這些前提成為謂詞,謂詞邏輯之間用的是“&&”“||”等而不是SQL中的and 、or。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQ_WHERE
{
  /// <summary>
  /// LINQ where子句
  /// </summary>
  class Program
  {
    static void Main(string[] args)
    {
      //1罕見的where語句
      List<GustInfo> gList = new List<GustInfo>() 
      {
        new GustInfo(){ Name="DebugLZQ", Age=26,Tel="88888888"},
        new GustInfo(){ Name="cnblogs",Age=6,Tel="666666"},
        new GustInfo(){ Name="M&MSoft",Age=9,Tel="55555"}
      };

      var query = from gust in gList
            where (gust.Name.Length > 7 || gust.Name.Substring(0, 1) == "M") && gust.Age > 9
            select new { gust.Name, gust.Age };
      foreach (var g in query)
      {
        Console.WriteLine("{0},{1}", g.Name, g.Age);
      }

      Console.ReadKey(false);

      //2.在where子句中應用自界說函數
      var query2 = from GustInfo gust in gList
             where gust.Name.Length > 5
             && Check(gust.Name)
             select gust;
      foreach (var g in query2)
      {
        Console.WriteLine("{0},{1},{2}", g.Name, g.Age, g.Tel);
      }
      Console.ReadKey(false);

      //3.靜態謂詞的挑選
      //界說靜態謂詞數組,在現實開辟中可以靜態取得
      string[] names = { "SB","XXX","***","@@@","一些敏感詞"};

      var query3 = from GustInfo guest in gList
             where !names.Contains(guest.Name)
             select guest;

      foreach (var q in query3)
      {
        Console.WriteLine("{0} 年紀:{1},德律風:{2}",q.Name,q.Age,q.Tel );
      }
      Console.ReadKey(false);
    }

    //自界說函數
    static bool Check(string name)
    {
      if (name.Substring(0, 1) == "N")
        return false;
      return true;
    }
  }
}

須要留意一些經常使用的where子句的寫法。法式的運轉成果以下:

201637153755441.png (677×442)

3.Select子句
在select子句上可以異常靈巧的處置查詢到的元素,然後再把成果前往。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQ_select
{
  /// <summary>
  /// LINQ select
  /// 在select子句上,可以異常靈巧的處置查詢到的元素,然後再把成果前往
  /// </summary>
  class MyGustInfo
  {
    public string Name { get; set; }
    public int Age { get; set; }
  }
  class Program
  {
    static void Main(string[] args)
    {
      List<GustInfo> gList = new List<GustInfo>() 
      {
        new GustInfo(){ Name="DebugLZQ", Age=25, Tel="88888888"},
         new GustInfo(){ Name="cnblogs", Age=6, Tel="666666"},
         new GustInfo(){ Name="M&M", Age=9, Tel="55555"}
      };
      var query = from gust in gList
            where gust.Age >= 9 && gust.Age <= 30
            select gust.Name.WordStr("&", "mm");//select子句靈巧運用
      var query2 = from gust in gList
             where gust.Age >= 9 && gust.Age <= 30
             select MyProc(gust.Name);
      var query3 = from gust in gList
             where gust.Age >= 9 && gust.Age <= 30
             select new { gust.Name,gust.Age};

      var query4 = from gust in gList
             where gust.Age >= 9 && gust.Age <= 30
             select new MyGustInfo { Name=gust.Name+"My", Age=gust.Age+1};//對查詢成果停止投影

      foreach (var v in query)
      {
        Console.WriteLine(v);
      }
      foreach (var v in query2)
      {
        Console.WriteLine(v);
      }
      foreach (var v in query3)
      {
        Console.WriteLine(v.Name+v.Age );
      }
      foreach (var v in query4)
      {
        Console.WriteLine(v.Name+v.Age );
      }

      Console.ReadKey(false);
    }
    static string MyProc(string s)
    {
      return s + "Better";
    }
  }
}

法式的運轉成果以下:

 4.group子句
 依據語法的劃定,LINQ表達式必需以from子句開首,以select或group子句停止,所以除應用select來前往成果外,也能夠應用group子句來前往元素分組後的成果。

group子句前往的是一個基於IGrouping<TKey,TElement>泛型接口的對象序列。

語法和SQL的group有點差別,不留意的話能夠會寫錯。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQ_group
{
  /// <summary>
  /// LINQ group子句
  /// </summary>
  class Program
  {
    static void Main(string[] args)
    {
      List<GustInfo> gList = new List<GustInfo>() 
      {
        new GustInfo(){ Name="DebugLZQ",Age=26,Tel="187********"},
        new GustInfo(){ Name="Sarah",Age=25,Tel="159********"},
        new GustInfo(){ Name="Jerry",Age=35,Tel="135********"},
        new GustInfo(){ Name="M&M",Age=16,Tel="136********"},
        new GustInfo(){ Name="DebugMan",Age=26,Tel="136********"},
        new GustInfo(){ Name="Jerry&Tom",Age=19,Tel="136********"},
      };

      var query = from guest in gList
            group guest by guest.Name.Substring(0, 1);//分組鍵key是string類型

      //遍歷鍵值和鍵值所屬元素
      foreach (IGrouping<string, GustInfo> guestGroup in query)
      {
        Console.WriteLine("分組鍵:{0}",guestGroup.Key );
        foreach (var g in guestGroup)
        {
          Console.WriteLine("{0} 年紀:{1} 德律風:{2}",g.Name,g.Age,g.Tel );
        }
      }
      Console.ReadKey(false);

      Console.WriteLine("-----------------------------------");

      var query2 = from guest in gList
             group guest by guest.Age > 20;//分組鍵key是bool類型表達式的成果

      foreach (IGrouping<bool, GustInfo> guestGroup in query2)
      {
        Console.WriteLine("年紀能否年夜於20 分組鍵:{0}", guestGroup.Key);
        foreach (var g in guestGroup)
        {
          Console.WriteLine("{0} 年紀:{1} 德律風:{2}", g.Name, g.Age, g.Tel);
        }
      }
      Console.ReadKey(false);
    }
  }
}

法式的運轉成果以下:

201637153931581.png (677×442)

5.into子句
 into子句作為一個暫時標識符,用於group、select、join子句中充任其成果的援用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQ_into
{
  /// <summary>
  /// LINQ group
  /// </summary>
  class Program
  {
    static void Main(string[] args)
    {
      List<GustInfo> gList = new List<GustInfo>() 
      {
        new GustInfo(){ Name="DebugLZQ",Age=26,Tel="187********"},
        new GustInfo(){ Name="Sarah",Age=25,Tel="159********"},
        new GustInfo(){ Name="Jerry",Age=35,Tel="135********"},
        new GustInfo(){ Name="M&M",Age=16,Tel="136********"},
        new GustInfo(){ Name="DebugMan",Age=26,Tel="136********"},
        new GustInfo(){ Name="Jerry&Tom",Age=19,Tel="136********"},
      };

      //1.into用於group子句
      var query = from guest in gList
            group guest by guest.Name.Substring(0, 1) into grguest
            orderby grguest.Key descending
            select grguest;

      var query2 = from guest in gList
            group guest by guest.Name.Substring(0, 1) into grguest
            orderby grguest.Key ascending 
            select grguest;

      //2.select 子句中的into子句
      var query3 = from guest in gList
             select new { NewName = guest.Name, NewAge = guest.Age } into newguest
             orderby newguest.NewAge
             select newguest;

      foreach (var guestGroup in query)
      {
        Console.WriteLine("分組鍵:{0}",guestGroup.Key );
        foreach (var g in guestGroup)
        {
          Console.WriteLine("{0} 德律風:{1}",g.Name,g.Tel );
        }
      }
      Console.ReadKey(false);

      foreach (var newg in query3)
      {
        Console.WriteLine("{0} 年紀:{1}",newg.NewName,newg.NewAge );
      }

      Console.ReadKey(false);
    }
  }
}

法式運轉成果以下:

201637154008267.png (677×442)

6.orderby子句、thenby子句
 LINQ可以依照元素的一個或多個屬性對元素停止排序。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQ_orderby
{
  class Program
  {
    /// <summary>
    /// LINQ orderby (ascending descending)
    /// </summary>
    /// <param name="args"></param>
    static void Main(string[] args)
    {
      List<GustInfo> gList = new List<GustInfo>() 
      {
        new GustInfo(){ Name="DebugLZQ",Age=26,Tel="187********"},
        new GustInfo(){ Name="Sarah",Age=25,Tel="159********"},
        new GustInfo(){ Name="Jerry",Age=35,Tel="135********"},
        new GustInfo(){ Name="M&M",Age=16,Tel="136********"},
        new GustInfo(){ Name="DebugMan",Age=26,Tel="136********"},
        new GustInfo(){ Name="Jerry&Tom",Age=19,Tel="136********"},
      };

      //依照年紀排序
      var query = from guest in gList
            orderby guest.Age
            select guest;
      var query1 = from guest in gList
             orderby guest.Age ascending
             select guest;
      var query2 = from guest in gList
             orderby guest.Age descending
             select guest;
      //依照年紀停止排序,依照名字字數停止主要排序
      var query3 = from guest in gList
            orderby guest.Age, guest.Name.Length
            select guest;
      var query4 = from guest in gList
             orderby guest.Age descending , guest.Name.Length ascending 
             select guest;
      var query5 = from guest in gList
             orderby guest.Age, guest.Name.Length,guest.Tel 
             select guest;

      foreach (var guest in query2)
      {
        Console.WriteLine("{0} 年紀:{1} 德律風:{2}",guest.Name,guest.Age,guest.Tel );
      }
      Console.ReadKey(false);
      foreach (var guest in query4)
      {
        Console.WriteLine("{0} 年紀:{1} 德律風:{2}", guest.Name, guest.Age, guest.Tel);
      }
      Console.ReadKey(false);
    }
  }
}

法式運轉成果以下:

201637154108735.png (677×442)

7.let子句
let子句用於在LINQ表達式中存儲子表達式的盤算成果。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQ_let
{
  /// <summary>
  /// LINQ let用來存子儲表達式的盤算成果
  /// </summary>
  class Program
  {
    static void Main(string[] args)
    {
      List<GustInfo> gList = new List<GustInfo>() 
      {
        new GustInfo(){ Name="DebugLZQ",Age=26,Tel="187********"},
        new GustInfo(){ Name="Sarah",Age=25,Tel="159********"},
        new GustInfo(){ Name="Jerry",Age=35,Tel="135********"},
        new GustInfo(){ Name="M&M",Age=16,Tel="136********"},
        new GustInfo(){ Name="DebugMan",Age=26,Tel="136********"},
        new GustInfo(){ Name="Jerry&Tom",Age=19,Tel="136********"},
      };

      //應用let子句創立規模變量g,並經由過程g構建查詢表達式
      var query = from guest in gList
            let g = guest.Name.Substring(0, 1)
            where g == "D" || g == "J"
            select guest;
      //也能夠不應用let,下面的語句等效於下
      var query2 = from guest in gList
             where guest.Name.Substring(0, 1) == "D" || guest.Name.Substring(0, 1) == "J"
             select guest;

      foreach (var g in query)
      {
        Console.WriteLine("{0} 年紀:{1} 德律風:{2}",g.Name,g.Age,g.Tel );
      }
      Console.ReadKey(false);
      Console.WriteLine("不應用let,等效的語句成果");
      foreach (var g in query2)
      {
        Console.WriteLine("{0} 年紀:{1} 德律風:{2}", g.Name, g.Age, g.Tel);
      }
      Console.ReadKey(false);
    }
  }
}

法式的運轉成果以下:

201637154137605.png (677×442)

8.join子句
假如一個數據源中元素的某個屬性可以跟別的一個數據源的中元素的某個屬性停止相等比擬,那末這兩個數據源可以用join子句停止聯系關系。

join子句應用equals症結字停止相等比擬,而不是經常使用的雙等號。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQ_join
{
  class Program
  {
    static void Main(string[] args)
    {
      //界說兩個數據源
      List<GustInfo> gList = new List<GustInfo>() 
      {
        new GustInfo(){ Name="DebugLZQ",Age=26,Tel="187********"},
        new GustInfo(){ Name="Sarah",Age=25,Tel="159********"},
        new GustInfo(){ Name="Jerry",Age=35,Tel="135********"},
        new GustInfo(){ Name="M&M",Age=16,Tel="136********"},
        new GustInfo(){ Name="DebugMan",Age=26,Tel="136********"},
        new GustInfo(){ Name="Jerry&Tom",Age=19,Tel="136********"},
      };

      List<GuestTitle> titleList = new List<GuestTitle>() 
      {
        new GuestTitle(){Name="DebugLZQ",Title="Soft Engineer"},
        new GuestTitle(){Name="DebugLZQ",Title="Team Leader"},
        new GuestTitle(){Name="Sarah",Title="Test Engineer"},
        new GuestTitle(){Name="Jerry",Title="Head Master"}
      };
      //1.依據姓名停止內銜接
      var query = from guest in gList
            join title in titleList on guest.Name equals title.Name
            select new { Name=guest.Name ,Title=title.Title,Age=guest.Age };

      foreach (var g in query)
      {
        Console.WriteLine("{0} {1} 年紀:{2}",g.Name,g.Title ,g.Age );
      }
      Console.ReadKey(false);

      //後面的多個from完成雷同的感化:與內銜接差別在於:這個中央的操作是叉乘取得笛卡爾積
      var query2=from guest in gList 
            from title in titleList 
            where guest.Name==title.Name
            select new { Name = guest.Name, Title = title.Title, Age = guest.Age };

      foreach (var g in query2)
      {
        Console.WriteLine("{0} {1} 年紀:{2}", g.Name, g.Title, g.Age);
      }
      Console.ReadKey(false);

      //2.依據姓名停止分組銜接
      //依據名字分組後,獲得每一個名字下的全體稱號
      var query3 = from guest in gList
             join title in titleList on guest.Name equals title.Name into tgroup
             select new { Name=guest.Name,Titles=tgroup };

      foreach (var g in query3)
      {
        Console.WriteLine(g.Name);
        foreach (var g2 in g.Titles)
        {
          Console.WriteLine("  {0}",g2.Title );
        }
      }
      Console.ReadKey(false);
      //3.依據姓名停止左外銜接
      //無職務的輸入為空白
      var query4 = from guest in gList
             join title in titleList on guest.Name equals title.Name into tgroup
             from subtitle in tgroup.DefaultIfEmpty()
             select new { Name=guest.Name,Title=subtitle==null?"空白":subtitle.Title };
      foreach (var g in query4)
      {
        Console.WriteLine("{0} {1} ",g.Name ,g.Title );
      }
      Console.ReadKey(false);
      
    }
  }
}

法式成果以下:

201637154220463.png (677×442)

以上就是LINQ的根本子句的經常使用用法,文字不是許多,由於代碼中都有具體的正文解釋。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved