DataTableExtensions.AsEnumerable(DataTable) Method

Definition

Returns an IEnumerable<T> object, where the generic parameter T is DataRow. This object can be used in a LINQ expression or method query.

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

Parameters

source
DataTable

The source DataTable to make enumerable.

Returns

An IEnumerable<T> object, where the generic parameter T is DataRow.

Exceptions

The source DataTable is null.

Examples

In the following sample, the DisplayProducts method receives a DataTable that contains a DataColumn named ProductName, extracts the ProductName values and then prints the values.

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);
   }
}

Remarks

Language-Integrated Query (LINQ) queries work on data sources that implement the IEnumerable<T> interface or the IQueryable interface. The DataTable class does not implement either interface, so you must call the AsEnumerable method to use the DataTable as a source in the From clause of a LINQ query. You can also obtain custom, domain-specific operators, such as CopyToDataTable, by returning an IEnumerable<T> object.

The enumerable object returned by the AsEnumerable method is permanently bound to the DataTable that produced it. Multiple calls to the AsEnumerable method will return multiple, independent queryable objects that are all bound to the source DataTable.

Applies to

Product Versions
.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.0 (package-provided), 2.1