开发者

field<t> invalid cast

开发者 https://www.devze.com 2022-12-28 12:33 出处:网络
I\'m having problems when using linq on a datatable.asenumerable(). This throws InvalidCastException. DateTime date=r.Field开发者_Python百科<DateTime>(\"date\");

I'm having problems when using linq on a datatable.asenumerable().

This throws InvalidCastException.

DateTime date=r.Field开发者_Python百科<DateTime>("date");

This works fine.

DateTime date = DateTime.Parse(r.Field<string>("date"));

What am I missing?

Regards Sven


Why would you expect it to work? The following code doesn't compile:

DateTime dt1 = (DateTime)"2004-01-01";

Whereas this does:

DateTime dt1 = DateTime.Parse("2004-01-01");

As in, you can't just cast a string to a DateTime, so if your value is a string, you need to explicitly convert it.


Are you sure your "date" column is of type DateTime?

This test code works as expected:

        DataTable dt = new DataTable();

        dt.Columns.Add(new DataColumn("date", typeof(DateTime)));

        for (int i = 0; i < 10; i++)
        {
            DataRow row = dt.NewRow();
            row["date"] = DateTime.Now.AddDays(i);
            dt.Rows.Add(row);
        }

        foreach (var r in dt.AsEnumerable())
        {
            DateTime d = r.Field<DateTime>("date"); // no problems here!

            Console.Write(d.ToLongDateString());
        }


Cast works between related types. string and date don't belong to same hierarchy & hence no direct translation is possible.

You can use cast, when you are sure that the types are related and conversion is possible.

Parse is different than cast.
i.e you are telling the runtime to see if it can be parsed to make a date out of it (per your example).

0

精彩评论

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

关注公众号