Search code examples
c#listlinqdatatabledatacolumn

Get DataTime DataColumn of DataTable to List


I want to get a DataColumn (of DataTime type) of my DataTable in List. How can I do this with LINQ?

I tried the following lines but didn't work:

DateTimeList = dt.Columns.Cast<DataColumn>()
   .Where(dc => dc.DataType == typeof(DateTime)).ToList());

DateTime values are created like the follow one:

new DateTime(2019, 6, 17, 16, 46, 05)

Solution

  • To return a List<DateTime> type from the DateTime columns in a DataTable:

    var dates = dt.Columns.Cast<DataColumn>()
        .Where(c => c.DataType == typeof(DateTime))
        .SelectMany(c => c.Table.Rows.Cast<DataRow>()
        .Select(r => r.Field<DateTime>(c.ColumnName))).ToList();
    

    The query gets all the DateTime values whether the dt contains one or more Column<DateTime> type.

    If you have a single DataColumn<DateTime> type in the table, you can write instead:

    var dates = dt.Rows
        .Cast<DataRow>()
        .Select(r => r.Field<DateTime>(dt.Columns.Cast<DataColumn>()
        .FirstOrDefault(c => c.DataType == typeof(DateTime))?.ColumnName)).ToList();