C# LINQ 與 Lambda 筆記

April 10, 2022

在寫 C# 程式時,常常會看到結合 LINQ 和 Lambda 語法的程式碼,以下是簡單的介紹。

LINQ 語法

  • 使用類似 SQL 的語法,常撰寫資料庫語法的人,可提高熟悉度。
  • 可直接對物件操作,查詢結果也為可操作的物件集合。
  • 常用的運算子: FROM, SELECT, WHERE 等,以下是一個基本的查詢語法。
var p = from a in emp
where a.country.Equals("america")
select a.name;

Lambda 語法

  • 可用來建立匿名函式。透過委派的方式傳入需要的資料。以下是一個基本的語法,從中取得集合 a 裡國家為台灣的資料,並以匿名型別呈現:
var q = emp.Where(x => x.country.Equals("taiwan"));

範例程式碼

using System;
using System.Linq;
					
public class Program
{
	public class employee{
		public string name;
		public string country;
		
		public employee(string n, string c){
			this.name = n;
			this.country = c;
		}
	}
	
	public static void Main()
	{
		employee[] emp = new employee[3];
		emp[0] = new employee("jacky", "taiwan");
		emp[1] = new employee("annie", "america");
		emp[2] = new employee("jeff", "taiwan");
		var q = emp.Where(x=>x.country.Equals("taiwan"));
		
		foreach(var t in q.AsEnumerable()){
			Console.WriteLine(t.name + ": " + t.country);
		}
		
		var p = from a in emp
			where a.country.Equals("america")
			select a.name;
		
		foreach(var t in p.AsEnumerable()){
			Console.WriteLine(t.ToString());
		}
	}
}

其它 Lambda 語法說明

  • 如果需要傳入多個參數時,必須加上括號。
int a = 3, b = 5;
Func<int, int, int> rect = (x, y) => x * y; // Func<T, T, TResult> 委派
Console.WriteLine(rect(a, b));
  • 如果需要指定明確型別時 (例如編譯器無法判斷輸入參數的類型),也要使用括弧。
Func<int, string, bool> isEqualLength = (int x, string s) => s.Length == x; 
Console.WriteLine(isEqualLength(3, "super"));
  • 只有單行時不必用 {} 包住程式,稱為 Lambda Expression;有多行時需用 {} 包住,稱為 Lambda Statements。

曾遇到的須注意部分

  • 要從 LINQ 的查詢結果取得第一筆資料,使用 .First().FirstOrDefault 時,如果沒有資料會拋出例外。另外也要避免重複呼叫 .First().Count() 方法,避免重複進行查詢。

參考資料