无法将类型为"系统.日期时间"的对象强制转换为类型"系统.字符串"错误



我有这个代码:

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;
}
}

我得到的错误是:

无法将"System.DateTime"类型的对象强制转换为"System.String"类型

为了克服这一点,我尝试了:

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

但是错误仍然存在。

我试过使用DateTime,但当我写它时,它给了我另一个错误,说

运算符==不能用于DateTime和字符串

请注意:WeekOffDays列的类型为日期时间

如何解决这个问题?

您不需要在其中字符串,它应该是

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

这是我尝试在本地机器上复制的方法。

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;
}

最新更新