Rohan
Rohan

Reputation: 314

LINQ Error unable to cast object of type 'system.datetime' to type 'system.string'

I am executing this code where i am getting the error.

Here is the query executed in the asp script. mydateTime contains both date & time value, so i am using CAST to get only date.

SELECT CAST(mydateTime AS DATE) AS getdate FROM vTable

Here is the code

var value = (from r in innerdt.AsEnumerable()
           where r.Field<string>("ggg") == dt.Rows[i][5].ToString()
           select r[0]);

Here innerdt is the Datatable & dt is another datatable. I am getting the error in select r[0]

How can i solve the problem ?

Thanks

Upvotes: 0

Views: 5722

Answers (1)

RePierre
RePierre

Reputation: 9566

Your innerdt table contains a column which is of type DateTime but when you query it via r.Field<string>("ggg") you want to convert it to a string.

This is where the problem is; method Field casts the value of the field to the value of the type you specify so the Field method would look something like:

public TDest Field<TDest>(this DataRow row, string key)
{
    var value = row[key];
    return (TDest)value; // Here it throws the InvalidCastException
}

What you need to do is to convert the DateTime to a string after fetching it from the row, like this:

var value = (from r in innerdt.AsEnumerable()
             where r.Field<DateTime>("ggg").ToString() == dt.Rows[i][5].ToString()
             select r[0]);

As a side note, keep in mind that this will compare dates to milliseconds which may not be what you want. To avoid this either use a format string to make sure that ToString() returns only the parts you want or use ToShortDateString().

EDIT

As @sloth suggested, a better approach would be to convert dt.Rows[i][5] to DateTime and then compare the objects using Date property; furthermore, you're better off with storing that value in a variable as you'll gain up on readability:

var desiredDate = Convert.ToDateTime(td.Rows[i][5]);
var value = (from r in innerdt.AsEnumerable()
             where r.Field<DateTime>("ggg").Date == desiredDate.Date
             select r[0]);

Upvotes: 1

Related Questions