LINQ基礎(一)

来源:http://www.cnblogs.com/afei-24/archive/2017/05/11/6841361.html
-Advertisement-
Play Games

LINQ(Language Integrated Query,語言集成查詢),在C#語言中集成了查詢語法,可以用相同的語法訪問不同的數據源。 LINQ提供了不同數據源的抽象層,所以可以使用相同的語法。 這裡主要介紹LINQ的核心原理和C#中支持C# LINQ查詢的語言擴展。 1.語法 使用LINQ查 ...


  LINQ(Language Integrated Query,語言集成查詢),在C#語言中集成了查詢語法,可以用相同的語法訪問不同的數據源。
  LINQ提供了不同數據源的抽象層,所以可以使用相同的語法。
  這裡主要介紹LINQ的核心原理和C#中支持C# LINQ查詢的語言擴展。

1.語法
  使用LINQ查詢出來自巴西的所以世界冠軍。這裡可以使用List<T>類的FindAll()方法,但使用LINQ查詢語法更簡單  

    static void LINQQuery()
        {
          //
          var query = from r in Formula1.GetChampions()
                      where r.Country == "Brazil"
                      orderby r.Wins descending
                      select r;

          foreach (var r in query)
          {
            Console.WriteLine("{0:A}", r);
          }

        }    

  變數query只指定了LINQ查詢。該查詢不是通過這個賦值語句執行的,而是使用foreach迴圈訪問查詢時執行的。

2.擴展方法
  編譯器會轉換LINQ查詢,以調用方法而不是LINQ查詢。LINQ為IEnumerable<T>介面提供了各種擴展方法(擴展方法在http://www.cnblogs.com/afei-24/p/6703843.html介紹到),以便用戶在實現了該介面的任意集合上使用LINQ查詢。
  定義LINQ擴展方法的一個類是System.Linq名稱空間中的Enumerable。只需要導入這個名稱空間,就打開了這個類的擴展方法的作用域。下麵是Where()擴展方法的實現代碼:

    public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source,Func<TSource,bool> predicate)
        {
            foreach(TSource item in source)
            {
                if(predicate(item))
                {
                    yield return item;
                }
                
            }
        }

  因為Where()作為一個泛型方法,所以它可以用於包含在集合中的任意類型。實現了IEnumerable<T>介面的任意集合都支持它。

3.推遲查詢的執行
  前面提到,在運行期間定義LINQ查詢表達式時,查詢不會運行。查詢在迭代數據項時才會運行。
  舉個例子:  

    static void DeferredQuery()
        {
          var names = new List<string> { "Nino", "Alberto", "Juan", "Mike", "Phil" };

          var namesWithJ = from n in names
                           where n.StartsWith("J")
                           orderby n
                           select n;

          Console.WriteLine("First iteration");
          foreach (string name in namesWithJ)
          {
            Console.WriteLine(name);
          }
          Console.WriteLine();

          names.Add("John");
          names.Add("Jim");
          names.Add("Jack");
          names.Add("Denny");

          Console.WriteLine("Second iteration");
          foreach (string name in namesWithJ)
          {
            Console.WriteLine(name);
          }

        }

 

  輸出:
  
  因為查詢在迭代時才執行,所以在第一次輸出後有添加項再輸出,會顯示又添加的項。

  但在調用方法ToArray(),ToList等方法時,不會延遲執行:  

    static void NotDeferredQuery()
        {
            var names = new List<string> { "Nino", "Alberto", "Juan", "Mike", "Phil" };

            var namesWithJ = (from n in names
                             where n.StartsWith("J")
                             orderby n
                             select n).ToList();

            Console.WriteLine("First iteration");
            foreach (string name in namesWithJ)
            {
                Console.WriteLine(name);
            }
            Console.WriteLine();

            names.Add("John");
            names.Add("Jim");
            names.Add("Jack");
            names.Add("Denny");

            Console.WriteLine("Second iteration");
            foreach (string name in namesWithJ)
            {
                Console.WriteLine(name);
            }

        }

  輸出:
  




下麵是用到的類,後續的也需要用到這些代碼。

//這個類創建需要的列表
        public static class Formula1
          {
            private static List<Racer> racers;
            //返回一組賽車手
            public static IList<Racer> GetChampions()
            {
              if (racers == null)
              {
                racers = new List<Racer>(40);
                racers.Add(new Racer("Nino", "Farina", "Italy", 33, 5,
           new int[] { 1950 }, new string[] { "Alfa Romeo" })); racers.Add(new Racer("Alberto", "Ascari", "Italy", 32, 10,
          new int[] { 1952, 1953 }, new string[] { "Ferrari" })); racers.Add(new Racer("Juan Manuel", "Fangio", "Argentina", 51, 24,
           new int[] { 1951, 1954, 1955, 1956, 1957 }, new string[] { "Alfa Romeo", "Maserati", "Mercedes", "Ferrari" })); racers.Add(new Racer("Mike", "Hawthorn", "UK", 45, 3,
           new int[] { 1958 }, new string[] { "Ferrari" })); racers.Add(new Racer("Phil", "Hill", "USA", 48, 3,
           new int[] { 1961 }, new string[] { "Ferrari" })); racers.Add(new Racer("John", "Surtees", "UK", 111, 6,
           new int[] { 1964 }, new string[] { "Ferrari" })); racers.Add(new Racer("Jim", "Clark", "UK", 72, 25,
          new int[] { 1963, 1965 }, new string[] { "Lotus" })); racers.Add(new Racer("Jack", "Brabham", "Australia", 125, 14,
           new int[] { 1959, 1960, 1966 }, new string[] { "Cooper", "Brabham" })); racers.Add(new Racer("Denny", "Hulme", "New Zealand", 112, 8,
          new int[] { 1967 }, new string[] { "Brabham" })); } return racers; } private static List<Team> teams; //返回一組冠軍車隊 public static IList<Team> GetContructorChampions() { if (teams == null) { teams = new List<Team>() { new Team("Vanwall", 1958), new Team("Cooper", 1959, 1960), new Team("Ferrari", 1961, 1964, 1975, 1976, 1977, 1979, 1982, 1983, 1999,
                    2000, 2001, 2002, 2003, 2004, 2007, 2008), new Team("BRM", 1962), new Team("Lotus", 1963, 1965, 1968, 1970, 1972, 1973, 1978), new Team("Brabham", 1966, 1967), new Team("Matra", 1969), new Team("Tyrrell", 1971), new Team("McLaren", 1974, 1984, 1985, 1988, 1989, 1990, 1991, 1998), new Team("Williams", 1980, 1981, 1986, 1987, 1992, 1993, 1994, 1996, 1997), new Team("Benetton", 1995), new Team("Renault", 2005, 2006 ), new Team("Brawn GP", 2009), new Team("Red Bull Racing", 2010, 2011) }; } return teams; } private static List<Championship> championships; //返回GetChampionships類型的集合 public static IEnumerable<Championship> GetChampionships() { if (championships == null) { championships = new List<Championship>(); championships.Add(new Championship { Year = 1950, First = "Nino Farina", Second = "Juan Manuel Fangio", Third = "Luigi Fagioli" }); championships.Add(new Championship { Year = 1951, First = "Juan Manuel Fangio", Second = "Alberto Ascari", Third = "Froilan Gonzalez" }); championships.Add(new Championship { Year = 1952, First = "Alberto Ascari", Second = "Nino Farina", Third = "Piero Taruffi" }); championships.Add(new Championship { Year = 1953, First = "Alberto Ascari", Second = "Juan Manuel Fangio", Third = "Nino Farina" }); championships.Add(new Championship { Year = 1954, First = "Juan Manuel Fangio", Second = "Froilan Gonzalez", Third = "Mike Hawthorn" }); championships.Add(new Championship { Year = 1955, First = "Juan Manuel Fangio", Second = "Stirling Moss", Third = "Eugenio Castellotti" }); championships.Add(new Championship { Year = 1956, First = "Juan Manuel Fangio", Second = "Stirling Moss", Third = "Peter Collins" }); } return championships; } }

 

//車手類
    
    [Serializable]
      public class Racer : IComparable<Racer>, IFormattable
      {
        public Racer(string firstName, string lastName, string country, int starts, int wins)
          : this(firstName, lastName, country, starts, wins, null, null)
        {
        }
        public Racer(string firstName, string lastName, string country, int starts,
       int wins, IEnumerable<int> years, IEnumerable<string> cars) { this.FirstName = firstName; this.LastName = lastName; this.Country = country; this.Starts = starts; this.Wins = wins; this.Years = new List<int>(years); this.Cars = new List<string>(cars); } //單值屬性 public string FirstName { get; set; } public string LastName { get; set; } public string Country { get; set; } public int Wins { get; set; } public int Starts { get; set; } //多值屬性,車手可能多次獲得冠軍,所在的車隊也可能不同 public IEnumerable<string> Cars { get; private set; } public IEnumerable<int> Years { get; private set; } public override string ToString() { return String.Format("{0} {1}", FirstName, LastName); } public int CompareTo(Racer other) { if (other == null) return -1; return string.Compare(this.LastName, other.LastName); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { switch (format) { case null: case "N": return ToString(); case "F": return FirstName; case "L": return LastName; case "C": return Country; case "S": return Starts.ToString(); case "W": return Wins.ToString(); case "A": return String.Format("{0} {1}, {2}; starts: {3}, wins: {4}", FirstName, LastName, Country, Starts, Wins); default: throw new FormatException(String.Format("Format {0} not supported", format)); } } }

 

//獲得冠軍的車隊
        [Serializable]
        public class Team
        {
            public Team(string name, params int[] years)
            {
                this.Name = name;
                this.Years = new List<int>(years);
            }
            public string Name { get; private set; }
            public IEnumerable<int> Years { get; private set; }
        }
        
        
        //獲獎選手和年份
          public class Championship
          {
            public int Year { get; set; }
            public string First { get; set; }
            public string Second { get; set; }
            public string Third { get; set; }
          }

 



您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • BitBlt 該函數對指定的源設備環境區域中的像素進行位塊(bit_block)轉換,以傳送到目標設備環境。 BitBlt 該函數對指定的源設備環境區域中的像素進行位塊(bit_block)轉換,以傳送到目標設備環境。 函數原型 [DllImport("gdi32.dll")] public sta ...
  • 1、"~/x/xx.aspx?id=" + id string id=Request.Params["id"].ToString(); 2、Response.Redirect("x.aspx?id=1&flag=true") bool flag=Request.QueryString["flag"] ...
  • 本文 所用的 資源 下載地址 http://pan.baidu.com/s/1jHTRiU6 使用文檔要可以在 菜鳥學校 查看(也包括下載地址) http://www.runoob.com/memcached/window-install-memcached.html 下載與自己系統對應的版本解壓, ...
  • 前言: 1.這個隨筆實現了一個Ajax動態載入的例子。 2.使用.net 的MVC框架實現。 3.這個例子重點在前後臺交互,其它略寫。 開始: 1.控制器ActionResult代碼(用於顯示頁面) 2.前臺頁面主要代碼 說明:這個就是要展示數據的表格,裡面的欄位要和你建好的模型匹配。 <table ...
  • 最近,項目上涉及到了圖像壓縮,發現原有的圖像壓縮功能,雖然保證了圖像的大小300K以內,但是壓縮後的圖像看的不在清晰,並且,限定了圖片的Height或者是Width。 在CSDN上看到了一個壓縮演算法:http://blog.csdn.net/qq_16542775/article/details/5 ...
  • 基於TcpListener、HttpLister的簡單web server搭建及基礎認知 ...
  • 前言: 最近在開始嘗試使用dotnet core做開發,dotnet core發佈到1.1也越發成熟了,微軟提供的文檔也很詳細,跟著Getting started with ASP.NET Core MVC and Entity Framework Core using Visual Studio ...
  • 最近開發一個項目使用到.net mail組件發送郵件。在開發環境中一切正常,可是部署到阿裡雲伺服器上死活發送不出去,一直連接不上,或者報語法錯誤。 然後是各種折騰,各種測試,最後發現,使用ssl的時候只有25埠才能發送,非ssl的時候都正常。 項目使用的smtp伺服器是阿裡雲的企業郵箱,用的ssl ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...