LINQ 查詢介紹
查詢是一種從數據源檢索數據的表達式。查詢通常用專門的查詢語言來表示。隨著時間的推移,人們已經為各種數據源開發了不同的語言;例如,用于關系數據庫的 SQL 和用于 XML 的 XQuery。因此,開發人員不得不針對他們必須支持的每種數據源或數據格式而學習新的查詢語言。LINQ 通過提供一種跨各種數據源和數據格式使用數據的一致模型,簡化了這一情況。在 LINQ 查詢中,始終會用到對象。可以使用相同的基本編碼模式來查詢和轉換 XML 文檔、SQL 數據庫、ADO.NET 數據集、.NET 集合中的數據以及對其有 LINQ 提供程序可用的任何其他格式的數據。
查詢操作的三個部分
所有 LINQ 查詢操作都由以下三個不同的操作組成:
- 獲取數據源。
- 創建查詢。
- 執行查詢。
下面的示例演示如何用源代碼表示查詢操作的三個部分。為了方便起見,此示例將一個整數數組用作數據源;但其中涉及的概念同樣適用于其他數據源。本主題的其余部分也會引用此示例。
class IntroToLINQ
{
static void Main()
{
// The Three Parts of a LINQ Query:
// 1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
// 2. Query creation.
// numQuery is an IEnumerable<int>
var numQuery =
from num in numbers
where (num % 2) == 0
select num;
// 3. Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
}
}
{
static void Main()
{
// The Three Parts of a LINQ Query:
// 1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
// 2. Query creation.
// numQuery is an IEnumerable<int>
var numQuery =
from num in numbers
where (num % 2) == 0
select num;
// 3. Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
}
}
全站熱搜