Getting minimum - Min() - for DateTime column in a DataTable using LINQ to DataSets?
- by Jay Stevens
I need to get the minimum DateTime value of a column in a DataTable. The DataTable is generated dynamically from a CSV file, therefore I don't know the name of that column until runtime. Here is code I've got that doesn't work...
private DateTime GetStartDateFromCSV(string inputFile, string date_attr)
{
EnumerableRowCollection<DataRow> table = CsvStreamReader.GetDataTableFromCSV(inputFile, "input", true).AsEnumerable();
DateTime dt = table.Select(record => record.Field<DateTime>(date_attr)).Min();
return dt;
}
The variable table is broken out just for clarity. I basically need to find the minimum value as a DateTime for one of the columns (to be chosen at runtime and represented by date_attr).
I have tried several solutions from SO (most deal with known columns and/or non-DateTime fields). What I've got throws an error at runtime telling me that it can't do the DateTime conversion (that seems to be a problem with Linq?)
I've confirmed that the data for the column name that is in the string date_attr is a date value.