DataTableExtensions.AsEnumerable(DataTable) 方法

定義

傳回 IEnumerable<T> 物件,其中泛型參數 TDataRow。 此物件可用於 LINQ 運算式或方法查詢。

C#
public static System.Data.EnumerableRowCollection<System.Data.DataRow> AsEnumerable (this System.Data.DataTable source);

參數

source
DataTable

要成為可列舉的來源 DataTable

傳回

IEnumerable<T> 物件,其中泛型參數 TDataRow

例外狀況

來源 DataTablenull

範例

在下列範例中 DisplayProducts ,方法會收到包含名為 ProductNameDataColumn 的 DataTable,會擷取 ProductName 值,然後列印值。

C#
using System;
using System.Data;

class Program {
   public void DisplayProducts(DataTable table) {
      var productNames = from products in table.AsEnumerable() select products.Field<string>("ProductName");
      Console.WriteLine("Product Names: ");
      foreach (string productName in productNames) {
         Console.WriteLine(productName);
      }
   }

   static void Main(string[] args) {
      DataTable table = new DataTable();
      table.Columns.Add("ID");
      table.Columns.Add("ProductName");

      table.Rows.Add("1", "Chai");
      table.Rows.Add("2", "Queso Cabrales");
      table.Rows.Add("3", "Tofu");

      Program inst = new Program();
      inst.DisplayProducts(table);
   }
}

備註

Language-Integrated Query (LINQ) 查詢會在實作 IEnumerable<T> 介面或 IQueryable 介面的資料來源上運作。 類別 DataTable 不會實作任一介面,因此您必須呼叫 AsEnumerable 方法,以在 DataTable LINQ查詢的子句中使用 From 作為來源。 您也可以傳回 IEnumerable<T> 物件,以取得自訂的網域特定運算子,例如 CopyToDataTable

方法所 AsEnumerable 傳回的可列舉物件會永久繫結至 DataTable 產生它的 。 對 方法的 AsEnumerable 多個呼叫會傳回多個獨立的可查詢對象,這些物件全都系結至來源 DataTable

適用於

產品 版本
.NET Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.1