Getting minimum - Min() - for DateTime column in a DataTable using LINQ to DataSets?

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.

UPDATE: Stacktrace as requested:

System.InvalidCastException was unhandled by user code Message="Specified cast is not valid." Source="System.Data.DataSetExtensions" StackTrace: at System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value) at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName) at Presenter.Views.NetworkVisualizationDetailPresenter.<>c__DisplayClass1.<GetStartDateFromCSV>b__0(DataRow t) in Presenter\Views\NetworkVisualizationDetailPresenter.cs:line 194 at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext() at System.Linq.Enumerable.Min[TSource](IEnumerable`1 source) at System.Linq.Enumerable.Min[TSource,TResult](IEnumerable`1 source, Func`2 selector) atPresenter.Views.NetworkVisualizationDetailPresenter.GetStartDateFromCSV(String inputFile, String date_attr) in Presenter\Views\NetworkVisualizationDetailPresenter.cs:line 194 at Presenter.Views.NetworkVisualizationDetailPresenter.GetDynamicNetworkVisualizationData(String inputFile, Int32 dataMode, Int32 timeInterval, String date_attr, String entity_attr, String event_attr) in Views\NetworkVisualizationDetailPresenter.cs:line 123 at Presenter.Views.NetworkVisualizationDetail.Page_Load(Object sender, EventArgs e) in NetworkVisualizationDetail.aspx.cs:line 114 at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) InnerException:

-------------Problems Reply------------

Actually it seems like your problem is not in Linq, but in the data in your data table. If your error states that is can't do the DateTime conversion, your error most likely is generated here:


which isn't in Linq.

Check that all of your rows have the correct value in this column. Also, if you could dump your stack trace from the exception it would help..

UPD: Looking at the stack trace update, I can see the top 2 entries in it:

at System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value)
at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)

This most definitely confirms that the problem is not inside linq, but in the actual data that you're trying to convert. Second call is the exception message, definitely a data conversion problem:

Message="Specified cast is not valid."

I have just double checked, this code would work on a datatable, if the column type were DateTime.

table.Select(record => record.Field<DateTime>(date_attr)).Min();

But if the column type is string - it throws the exception you're getting, with the same stack trace! :)

Change it to this, and you shouldn't get any errors (that is considering your data is valid):

table.Select(record => Convert.ToDateTime(record[date_attr])).Min();

Category:c# Views:0 Time:2010-04-24

Related post

  • MySQL C#, last x mins from datetime column 2012-01-16

    Using MySQL and I have data being loaded into a table every second. I want to just see the latest x mins (10, 15, whatever I want). Everything I've read says to use INTERVAL and this works in the MySQL query editor BUT I'm querying the table from .NE

  • Get the minimum value between several columns 2011-09-29

    I'm using SQL Server 2008; Suppose I have a table 'X' with columns 'Date1', 'Date2', 'Dateblah', all of type DateTime. I want to select the min value between the three columns, for example (simplified, with date mm/dd/yyyy) ID Date1 Date2 Dateblah 0

  • How to build the sum of `DATETIME` columns? 2009-09-30

    I have a table with two DATETIME columns: Column1 Column2 1/1/1900 12:20:45 1/1/1900 23:22:25 1/1/1900 09:00:00 1/1/1900 18:10:30 … … (Times are in the format HH:MM:SS.) I want to take a total of column 1 and total of column 2. If the table had only

  • jqGrid error on sorting datetime column 2011-04-06

    When I set [ sorttype: "datetime", datefmt: "d/m/Y H:i:s" ] to a jQuery grid, I get a message error when sorting a datetime column. The message is: undefined. But, this only happens in IE 8/9, on Firefox it works fine. I have some tables created dyna

  • How to insert null value into DateTime column? 2011-09-12

    I am trying to store a null value into a DateTime column. My code is like below: protected void btnInsert_Click(object sender, EventArgs e) { try { ChangeModule cm = new ChangeModule(); cm.CR_REF_NO = txtCRRefNumber.Text.Trim(); cm.SLA_DELIVERY_DATE_

  • Remove the minimum values per each column of a Matrix 2012-02-05

    If I had a matrix A such as: 63 55 85 21 71 80 65 85 48 53 55 60 93 71 66 21 65 40 33 21 61 90 80 48 50 ... and so on how would I find the minimum values of each column and remove those numbers from the matrix completely, meaning essentially I would

  • max and min in multiple columns that some contain #N/A. 2012-04-05

    I am trying to calculate the max and min in multiple columns that contain #N/A. Formatting has the value hidden. cell formula is =IF('Input Data'!AJ7<>"",'Input Data'!AJ7+'Input Data'!AK7/60+'Input Data'!AL7/3600,#N/A). This formula cannot chan

  • search for the minimum value in a column and return the value from the corresponding cell in a different column on the same line 2013-01-05

    Looking for a type of formula. I want to search for the minimum value in a column and return the value from the corresponding cell in a different column on the same line. Make sense? --------------Solutions------------- 8slim =Index(B:B,Match(Max(A:A

  • How to type a formula for a minimum value, in a column, but above zero? 2014-05-24

    I would like to know how to type in a formula to find the minimum value in a column of numbers, but I want the value to be greater than zero. I am using Excel 2007. --------------Solutions------------- I would like to know how to type in a formula to

  • How do you set a default value for a MySQL Datetime column? 2008-10-03

    How do you set a default value for a MySQL Datetime column? In SQL Server it's getdate(). What is the equivalant for MySQL? I'm using MySQL 5.x if that is a factor. --------------Solutions------------- IMPORTANT EDIT: It is now possible to achieve th

  • Oracle database allows invalid time portion of datetime column values under what circumstances? 2008-10-15

    This case arises in a real-life situation where invalid data was in (and continuing to come into) an Oracle database which is extracted into a data processing system in Focus. Focus would choke and die on some rows with invalid time portions. The Ora

  • Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns? 2008-10-15

    I'm attempting to fulfill a rather difficult reporting request from a client, and I need to find away to get the difference between two DateTime columns in minutes. I've attempted to use trunc and round with various formats and can't seem to come up

  • Data binding formatting to a DateTime column 2008-10-30

    I have a textbox with the Text property bound to a dataset column with the DataType set to System.DateTime. The FormatString on the Binding is set to dd-MM-yyyy. When the user enters a date it attempts to convert it to a date but can come up with som

  • MS SQL: Convert Datetime column to nvarchar 2008-11-07

    I need to select a datetime column in a table. However, I want the select statement to return the datetime as a nvarchar with the format DD/MM/YYYY. --------------Solutions------------- Assuming sql server, here is the convert documentation: http://m

  • How can I write a where clause in SQL to filter a DATETIME column by the time of day? 2009-04-02

    I have data that is timestamped with a DATETIME column and I want to filter it down to the set of records where the DATETIME is between 9:30am and 5:30pm for any day. What's the best way to do this? UPDATE: Changed because I need precision to the min

  • DataGridView sorting with nulls in DateTime column 2009-05-15

    I've got a DataGridView control in a Windows forms application. There are four columns with string data and three with DateTime data. I'm adding the rows programmatically using the Rows.Add() method. All of the columns have SortMode set to Automatic.

  • I am using SQL Server 2008, is it ok to define an Index on a DateTime column? 2009-07-02

    I heard somewhere that declaring an Index on a date column is bad for performance, but I can't find any reference on the internet. Suggestions? --------------Solutions------------- DateTime in SQL Server 2005 (and in SQL Server 2008 too) is stored as

  • Ext JS GroupingStore group DateTime column by just date? 2009-08-04

    I have an Ext GroupingStore on a list of orders. One of the columns is a DateTime. I would like the user to be able to group by the DateTime column and have all days under one group. At the moment, each date, hour, minute and second is one group... n

  • Database name convention: DATETIME column 2009-09-04

    What is your naming convention for DATETIME columns (in my case, using MS SQL Server) For a column that stores when the row was created CreatedDatetime makes sense, or LastModifiedDatetime. But for a simple table, let's say one called Event, would yo

Copyright (C), All Rights Reserved.

processed in 0.205 (s). 11 q(s)