在學習程式語言的過程中,資料查詢是非常常見的需求。
過去如果我們要對陣列或集合做篩選、排序或轉換,往往要寫一堆 for 迴圈、if 條件,程式碼冗長又不好閱讀。
C# 提供的 LINQ (Language Integrated Query) 可以讓我們用更直觀的方式「查詢資料」,就像在資料庫寫 SQL 一樣,讓程式碼更簡潔、可讀性更高。
LINQ(發音為 "link")是 C# 語言內建的查詢功能,可以操作:
陣列(Array)
集合(List, Dictionary 等)
XML
資料庫(搭配 Entity Framework)
它的語法類似 SQL,支援 select、where、orderby 等關鍵字。
using System;
using System.Linq; // 一定要引用這個命名空間
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// 使用 LINQ 查詢偶數
var evenNumbers = from n in numbers
where n % 2 == 0
select n;
Console.WriteLine("偶數有:");
foreach (var n in evenNumbers)
{
Console.WriteLine(n);
}
}
}
輸出結果:
偶數有:
2
4
6
8
10
在程式碼當中from n in numbers:從陣列 numbers 取出每個元素 n。where n % 2 == 0:過濾出偶數。select n:選出這些符合條件的數字。