开发者

.NET LINQ foreach DATETIME cannot convert String to DateTime exception

I have SQL data table that containes a DATE or DATETIME field

a LINQ statement show here just to get the basic idea

var testLinq = from t in DBDataContext.Certificates select t;

    foreach (var t in testLinq)
    {
     ....
    }

Left out the code in {..} for briefness. BUT whenever 'foreach' tries to use t I get this exception

"Input string was not开发者_如何学运维 in a correct format." When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime Object

How can I do this when its handled by Linq inside the foreach loop?


First of all, make it like this

var testLinq = (from t in DBDataContext.Certificates select t).ToList();

foreach (var t in testLinq)
{
 ....
}

and convert your string to to datetime like this

DateTime dt = DateTime.Parse("yourString")

if its not working,

DateTime dt = new DateTime(year,month,day);

and get your year,month,day values with Convert.ToInt32(yourString.SubString(0,4)) etc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜