LINQ語法簡介 - 5

by vivid 18. 四月 2018 02:49

.NET Magazine國際中文電子雜誌
作 者:許薰尹
審 稿:張智凱
文章編號:
N180419402
出刊日期: 2018/4/18

在這篇文章中,將延續《LINQ語法簡介 - 1》、《LINQ語法簡介 - 2》、《LINQ語法簡介 - 3》與《LINQ語法簡介 - 4》文章的情境,介紹常用的LINQ運算子(Operator),以透過更簡易的語法來查詢陣列或集合中的內容,這一篇主要介紹轉換運算子,包含:「ToArray」、「ToList」、「ToDictionary」、「ToLookup」、「Cast」、「AsEnumerable」與「OfType」。

 

轉換運算子 – ToArray

轉型運算子可以根據需求將序列轉換成集合或陣列,「ToArray」方法用來轉換成陣列,參考以下範例程式碼,將「Customer」集合轉換成陣列,然後透過「foreach」迴圈印出陣列中「Customer」物件的客戶名稱「CustomerName」:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LINQDemo {
  class Customer {
    public int CustomerID { get; set; }
    public string CustomerName { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
    public int PostalCode { get; set; }
    public string Country { get; set; }
  }
  class Program {
    static void Main( string [] args ) {

      List<Customer> customers = new List<Customer> {
        new Customer(){ CustomerID = 1, CustomerName ="Mary" , ContactName = "Maria Anders" , City = "Berlin", PostalCode = 12209 , Country = "Germany" },
        new Customer(){ CustomerID = 2, CustomerName ="Ann" , ContactName = "Ana Trujillo" , City = "México ", PostalCode = 05021 , Country = "Mexico" },
        new Customer(){ CustomerID = 3, CustomerName ="Lili" , ContactName="Futterkiste" , City = "México ", PostalCode = 05023 , Country = "UK" }
      };
      Customer [] customersArray = customers.ToArray( );
      foreach ( var item in customersArray ) {
        Console.WriteLine(item.CustomerName);
      }
    }
  }
}

 

這個範例程式的執行結果參考如下:

clip_image002

圖 1:轉換算子 - 「ToArray」。

轉換運算子 – ToList

「ToList」用來將序列轉換成集合,參考以下範例程式碼,叫用「ToList」方法,將「Customer」陣列轉換成集合:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LINQDemo {
  class Customer {
    public int CustomerID { get; set; }
    public string CustomerName { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
    public int PostalCode { get; set; }
    public string Country { get; set; }
  }
  class Program {
    static void Main( string [] args ) {
      Customer [] customers = new Customer [] {
        new Customer(){ CustomerID = 1, CustomerName ="Mary" , ContactName = "Maria Anders" , City = "Berlin", PostalCode = 12209 , Country = "Germany" },
        new Customer(){ CustomerID = 2, CustomerName ="Ann" , ContactName = "Ana Trujillo" , City = "México ", PostalCode = 05021 , Country = "Mexico" },
        new Customer(){ CustomerID = 3, CustomerName ="Lili" , ContactName="Futterkiste" , City = "México ", PostalCode = 05023 , Country = "UK" }
      };
      List<Customer> customersArray = customers.ToList( );
      foreach ( var item in customersArray ) {
        Console.WriteLine(item.CustomerName);
      }
    }
  }
}

 

這個範例程式的執行結果參考如下:

clip_image002[1]

圖 2:轉換算子 - 「ToList」。

轉換運算子 – ToDictionary

「ToDictionary」可以將來源序列轉換成Dictionary類型的物件,叫用此方法時,需要利用Func委派指定分組鍵值(Key),參考以下範例程式碼,指定鍵值為「CustomerID」:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LINQDemo {
  class Customer {
    public int CustomerID { get; set; }
    public string CustomerName { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
    public int PostalCode { get; set; }
    public string Country { get; set; }
  }
  class Program {
    static void Main( string [] args ) {
      List<Customer> customers = new List<Customer> {
        new Customer(){ CustomerID = 1, CustomerName ="Mary" , ContactName = "Maria Anders" , City = "Berlin", PostalCode = 12209 , Country = "Germany" },
        new Customer(){ CustomerID = 2, CustomerName ="Ann" , ContactName = "Ana Trujillo" , City = "México ", PostalCode = 05021 , Country = "Mexico" },
        new Customer(){ CustomerID = 3, CustomerName ="Lili" , ContactName="Futterkiste" , City = "México ", PostalCode = 05023 , Country = "UK" }
      };

      IDictionary<int , Customer> dic = customers.ToDictionary( c => c.CustomerID );

      foreach ( var item in dic ) {
        Console.WriteLine( $" {item.Key} - {item.Value.CustomerName}" );
      }
    }
  }
}

 

這個範例程式的執行結果參考如下:

clip_image004

圖 3:轉換算子 - 「ToDictionary」。

轉換運算子 – ToLookup

「ToLookup」的用法和「GroupBy」一樣應用在資料分組,唯一的不同點是「GroupBy」是延遲執行查詢,而「ToLookup」是馬上執行查詢,參考以下範例程式碼,根據「Customer」的「City」做資料分組:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LINQDemo {
  class Customer {
    public int CustomerID { get; set; }
    public string CustomerName { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
    public int PostalCode { get; set; }
    public string Country { get; set; }
  }
  class Program {
    static void Main( string [] args ) {
      List<Customer> customers = new List<Customer> {
        new Customer(){ CustomerID = 1, CustomerName ="Mary" , ContactName = "Maria Anders" , City = "Berlin", PostalCode = 12209 , Country = "Germany" },
        new Customer(){ CustomerID = 2, CustomerName ="Ann" , ContactName = "Ana Trujillo" , City = "México ", PostalCode = 05021 , Country = "Mexico" },
        new Customer(){ CustomerID = 3, CustomerName ="Lili" , ContactName="Futterkiste" , City = "México ", PostalCode = 05023 , Country = "UK" }
      };

      ILookup<string , Customer> customerGroup = customers.ToLookup( c => c.City );

      foreach ( var g in customerGroup ) {
        Console.WriteLine(g.Key);
        foreach ( var item in g ) {
          Console.WriteLine( $" {item.CustomerName}" );
        }
      }
    }
  }
}

 

 

這個範例程式的執行結果參考如下:

clip_image006

圖 4:轉換算子 - 「ToLookup」。

轉換運算子 – Cast

「Cast」用來將序列轉換成「IEnumerable<T>」型別,參考以下範例程式碼展示如何轉換「Customer」陣列:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LINQDemo {
  class Customer {
    public int CustomerID { get; set; }
    public string CustomerName { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
    public int PostalCode { get; set; }
    public string Country { get; set; }
  }
  class Program {
    static void Main( string [] args ) {
      Customer [] customers = new Customer [] {
        new Customer(){ CustomerID = 1, CustomerName ="Mary" , ContactName = "Maria Anders" , City = "Berlin", PostalCode = 12209 , Country = "Germany" },
        new Customer(){ CustomerID = 2, CustomerName ="Ann" , ContactName = "Ana Trujillo" , City = "México ", PostalCode = 05021 , Country = "Mexico" },
        new Customer(){ CustomerID = 3, CustomerName ="Lili" , ContactName="Futterkiste" , City = "México ", PostalCode = 05023 , Country = "UK" }
      };

      IEnumerable<Customer> customersArray = customers.Cast<Customer>( );

      foreach ( var item in customersArray ) {
        Console.WriteLine( item.CustomerName );
      }
    }
  }
}

 

這個範例程式的執行結果參考如下:

clip_image007

圖 5:轉換算子 - 「Cast」。

轉換運算子 – AsEnumerable

「AsEnumerable」的用途和「Cast」一樣,用來將序列轉換成「IEnumerable<T>」型別,參考以下範例程式碼展示如何轉換「Customer」陣列:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LINQDemo {
  class Customer {
    public int CustomerID { get; set; }
    public string CustomerName { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
    public int PostalCode { get; set; }
    public string Country { get; set; }
  }
  class Program {
    static void Main( string [] args ) {
      Customer [] customers = new Customer [] {
        new Customer(){ CustomerID = 1, CustomerName ="Mary" , ContactName = "Maria Anders" , City = "Berlin", PostalCode = 12209 , Country = "Germany" },
        new Customer(){ CustomerID = 2, CustomerName ="Ann" , ContactName = "Ana Trujillo" , City = "México ", PostalCode = 05021 , Country = "Mexico" },
        new Customer(){ CustomerID = 3, CustomerName ="Lili" , ContactName="Futterkiste" , City = "México ", PostalCode = 05023 , Country = "UK" }
      };

      IEnumerable<Customer> customersArray = customers.AsEnumerable();

      foreach ( var item in customersArray ) {
        Console.WriteLine( item.CustomerName );
      }
    }
  }
}

 

這個範例程式的執行結果參考如下:

clip_image008

圖 6:轉換算子 - 「AsEnumerable」。

轉換運算子 – OfType

「OfType」運算子可以從陣列或集合中,找出指定型別的物件,放到集合中回傳,參考以下範例程式碼,找出集合中所有的字串:

List<object> list = new List<object> { 10 , "hello" , DateTime.Now , true , 'c' , 20 , "world" };
var result = from item in list.OfType<string>( )
select item;

foreach ( var item in result ) {
  Console.WriteLine(item);
}

這個範例程式的執行結果參考如下:

clip_image010

圖 7:轉換算子 - 「OfType」。

若改成擴充方法語法,則寫法如下:

List<object> list = new List<object> { 10 , "hello" , DateTime.Now , true , 'c' , 20 , "world" };
var result = list.OfType<string>( );
foreach ( var item in result ) {
  Console.WriteLine( item );
}

Tags:

.NET Magazine國際中文電子雜誌 | C# | 許薰尹Vivid Hsu

新增評論




  Country flag
biuquote
  • 評論
  • 線上預覽
Loading






NET Magazine國際中文電子雜誌

NET Magazine國際中文電子版雜誌,由恆逸資訊創立於2000,自發刊日起迄今已發行超過500篇.NET相關技術文章,擁有超過40000名註冊讀者群。NET Magazine國際中文電子版雜誌希望藉於電子雜誌與NET Developer達到共同學習與技術新知分享,歡迎每一位對.NET 技術有興趣的朋友們多多支持本雜誌,讓作者群們可以有持續性的動力繼續爬文。<請加入免費訂閱>

月分類Month List