1. 程式人生 > >C#LINQ介紹

C#LINQ介紹

前言

最近在自學C#的過程中,突然發現LINQ(Language Integrated Query)這個名詞,自己看了看MSDN,就決定摘錄其中個人認為比較用知識點,供大家學習參考。

  • 首先看看微軟MSDN的解釋:
A query is an expression that retrieves data from a data


 source. Queries are usually expressed in a specialized 

query language. Different languages have been developed 

over time
for the various types of data sources, for example SQL for relational databases and XQuery for XML. Therefore, developers have had to learn a new query language for each type of data source or data format that they must support. LINQ simplifies this situation by offering a consistent model for
working with data across various kinds of data sources and formats. In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, .NET collections, and any other format for which a
LINQ provider is available.

一大段英文,想必大家都不願意去看這些,但是我覺得這段英文是十分有用的,下來自己翻譯一下

一個查詢是一個表示式,從資料來源檢索資料。查詢通常表示在一個專門的查詢語


言。不同的語言已經發展了很長時間的各種型別的資料來源,比如關係資料庫的SQL


和XQuery XML。因此,開發人員不得不學習一種新的查詢語言對每個型別的資料

源或資料格式,他們必須支援。LINQ簡化這種情況提供了一個一致的模型在各種

資料來源和處理資料格式。在LINQ查詢,你總是使用物件。你使用相同的基本編碼

模式在XML文件的查詢和轉換資料,SQL資料庫、ADO。網路資料集。淨集合,和任

何其他格式的LINQ提供程式是可用的。
  • 查詢三步走
All LINQ query operations consist of three distinct actions:

Obtain the data source.

Create the query.

Execute the query.

舉例說明LINQ的使用

class Program
{
        static void Main(string[] args)
        {
            // Specify the data source.
            int[] scores = new int[] { 97, 92, 81, 60 };

            // Define the query expression.
            IEnumerable<int> scoreQuery =
                from score  in scores 
                where score > 80 
                select score;

            // Execute the query.
            foreach (int i in scoreQuery)
            {
                Console.Write(i + " ");
            }            
        }
   }
  • 程式碼之行結果如下:
    這裡寫圖片描述

  • 下面的插圖顯示了完整的查詢操作。在LINQ查詢的執行不同的查詢本身,換句話說你沒有任何資料只是通過建立一個查詢來檢索變數。

這裡寫圖片描述

以上為自己結合MSDN學習的點心得