datatable linq c# code example

Example 1: C# create DataTable

DataTable dt = new DataTable(); 
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");

DataRow _ravi = dt.NewRow();
_ravi["Name"] = "ravi";
_ravi["Marks"] = "500";
dt.Rows.Add(_ravi);

Example 2: c# datatable to linq

//You can't query against the DataTable's Rows collection, since 
//DataRowCollection doesn't implement IEnumerable<T>. 
//You need to use the AsEnumerable() extension for DataTable

var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow;


//AsEnumerable() returns IEnumerable<DataRow>. 
//If you need to convert IEnumerable<DataRow> to a DataTable,
//use the CopyToDataTable()

Example 3: linq datatable

//Reference System.Data.DataSetExtensions
//Be carefull to data types
int id = 1;
//one row
DataRow r = (from DataRow m in myTable.Rows where m.Field<int>("col_name") == id select m).FirstOrDefault();
//list of rows
List<DataRow> r = (from DataRow m in myTable.Rows where m.Field<int>("col_name") == id select m).ToList();

Example 4: datatables.net

Javascript123$(document).ready( function () {    $('#myTable').DataTable();} );