Rohan Rao
Rohan Rao

Reputation: 2603

Unable to cast object of type 'System.DateTime' to type 'System.String'” error

I have this code:

 public bool GetHolidays(DataSet ds,List<string> dates,DataTable dt)
    {
        for (int i = 0; i <= dates.Count; i++)
        {
            bool weekOff = ds.Tables[0].AsEnumerable().Where(x=>(x.Field<string>("WeekOffDays")==dates[i]).ToString()).Any(); // error in this line

            if(weekOf)
               return true;

            return false;
        }
     }

I get the error that says:

Unable to cast object of type 'System.DateTime' to type 'System.String'

To overcome this I tried:

   DateTime dateTime;
   bool weekOff = ds.Tables[0].AsEnumerable().Where(x=>DateTime.TryParse((x.Field<string> 
     ("WeekOffDays")==dates[i]).ToString(),out dateTime)).Any(); 

but still the error persists.

I tried with DateTime but when I write it, it gives me another error saying

Operator == cannot be used for DateTime and string

Please note: The column WeekOffDays is of type datetime

How this can be solved?

Upvotes: 0

Views: 537

Answers (1)

Hien Nguyen
Hien Nguyen

Reputation: 18975

You dont need toString in where, it should be

  bool weekOff = ds.Tables[0].AsEnumerable().Where(x => 
                    x.Field<string>("WeekOffDays") == dates[i]).Any();

This is method i tried reproduce in local machine.

public bool GetHolidays(DataSet ds, List<string> dates, DataTable dt)
        {
            for (int i = 0; i <= dates.Count; i++)
            {
                bool weekOff = ds.Tables[0].AsEnumerable().Where(x => x.Field<string>("WeekOffDays") == dates[i]).Any(); // error in this line

                if (weekOff)
                    return true;
            }
            return false;
        }

Upvotes: 0

Related Questions