Mike Bradley Mike Bradley - 1 month ago 8
C# Question

Create a list of DataTables from a single DataTable, but grouped by day

I hope someone can help me with this puzzling question!

In the past I've used the following statement in order to obtain a

List<DataTable>
where each
DataTable
in the list comprises of all the records for each of the distinct names in the "Name" column of the "inputDT" datatable.

In other words, this code outputs a list of tables where each table contains the data for a specific Name:

List<DataTable> listOfSerialNumberDataTables = inputDT.AsEnumerable().GroupBy(row => row.Field<string>("Name")).Select(g => g.CopyToDataTable()).ToList();


I now would like to do a similar thing, except I would like to group by a
DateTime
column, where each of the
DataTable
s in
List<DataTable>
comprises of the records which have the same date (regardless of time).

So I'm trying to create code which creates a list where a table in the
list<DataTable>
will contain all the data for a specific date.

So for example, one of the tables will contain all the data that is dated 1st Oct 2016, and another table in the list will contain the data for the 3rd Oct, etc. [PS I'm not worried about the format of the output of the column - this question is just about get a list of DataTables where the data in them is for a specific day.]

[Note - all of the dates are in the table. So I'm not expecting an empty list for a date that is not in the dataTable. Apologies if that's obvious!]

Where I'm at:
After much head-scratching I've come up with something similar to this, but I'm not sure how to finish it off:

List<DataTable> listOfDaysForSingleSerialNo = datatable.AsEnumerable().GroupBy(x => EntityFunctions.TruncateTime(x.Field<DateTime>("DateOfResult"))).<what goes here?>


I'm baffled. Can anybody help? Is this actually possible using LINQ?

Thank you in advance for your kind assistance everybody.

Answer

If I understand correctly you want to do the exact same thing except on a different column. So the only thing that should change is the expression going into the GroupBy() method:

List<DataTable> listOfDaysForSingleSerialNo = datatable.AsEnumerable().GroupBy(x => x.Field<DateTime>("DateOfResult").Date).Select(g => g.CopyToDataTable()).ToList();

EDIT: The EntityFunctions.TruncateTime method only works with LINQ to Entities (msdn), so the GroupBy() cannot use it. Instead you can just get the Date property of the DateTime.