简体   繁体   中英

Copying one datatable to another datatable c#

I have one datatable called dt which has columns like date ,name,subject . I want to copy part of this dt to another datatable dt3 using where condition.

foreach (DataRow row in dt.Rows)
{
      cellData =(DateTime)row["date"];
      dt3 =  dt.AsEnumerable()
               .Where (rows =>rows.Field<DateTime>("date")== cellData )
               .CopyToDataTable();
}

I am trying this ,but its giving exception. Please give a solution for this or else how to use by select query

You are trying to filter your table from each row. This is not correct and will create a datatable for every row.

If you want to filter your dataTable, you can use dt.Select() or use Linq :

var dateFilter = DateTime.Parse("1/1/2015");
var dt3 = dt.AsEnumerable().Where(x => x.Field<DateTime>("date") == dateFilter).CopyToDataTable();

Please provide more explanation if that's not exactly what you want to perform.

Datatable dt may have rows which has null values for column date

Use nullable DateTime while comparing date

 dt3 = dt.AsEnumerable()
              .Where(rows => rows.Field<DateTime?>("date") == cellData )
              .CopyToDataTable();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM