Linq结果整数错误:指定的转换无效。

3
以下是我的代码:
   DataTable dt = new DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {

        dt.Columns.Add("RowId");
        dt.Columns.Add("Amount");

        DataRow row = dt.NewRow();
        row[0] = "1";
        row[1] = "2000";

        dt.Rows.Add(row);

        GetRecord(1);
    }

    protected void GetRecord(int RowId)
    {
        var results = from row in dt.AsEnumerable()
        where row.Field<int>("RowId") == RowId
        select row;

        string FetchedRowId = results.ToArray()[0].ToString();
    }
}

当我使用这种方式时,它会出现错误:在以下行中指定的转换无效:
其中 TableRow.Field<int>("RowId") == RowId
但是当我进行转换后:
   protected void GetRecord(int RowId)
    {
        var results = from row in dt.AsEnumerable()
        where row.Field<string>("RowId") == RowId.ToString()
        select row;

        string FetchedRowId = results.ToArray()[0].ToString();
    }

它能够工作。为什么row.Field<int>无法工作?

1个回答

10
问题在于你没有指定列的类型为int。你可以使用Add(string, Type)方法来指定类型。
dt.Columns.Add("RowId", typeof(int));
dt.Columns.Add("Amount", typeof(int));

DataRow row = dt.NewRow();
// whether you add strings or ints here doesn't matter, it's converted
row[0] = "1";
row[1] = 2000;

将某个值分配给 row[0] 将尝试自动将该值转换为正确的数据类型,这是一种非常“隐晦”的特性 :| - King King
谢谢,它起作用了。Tim,在不使用typeof(int)的情况下,它考虑什么? - RKh
@RKh 默认数据类型是 string - King King
GetRecord(1)部分没问题,只是当你使用row.Field<int>("RowId")时,列的类型 (string) 和你尝试获取它的类型 (int) 之间的不匹配导致了问题。 - Tim S.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接