我正在进行一个C# ASP.NET项目。
我有一个MySQL表,其中包含一个类型为int
的userid字段。
现在我想使用LINQ获取userid值等于某个特定值的行数。
为了实现这一目标,我编写了以下方法:
public int getCount(int usercode) {
int count = 0;
DataTable mytable = getAllRowsAndReturnAsDataTable(); // assigning a DataTable value to mytable.
if (mytable.Rows.Count > 0) {
count = (from x in mytable.AsEnumerable() where x.Field<Int32>("userid") == usercode select x).Count();
}
return count;
}
但它显示错误System.InvalidCastException: Specified cast is not valid.
,在红色高亮区域中显示count = (from x in mytable.AsEnumerable() where x.Field<Int32>("userid") == usercode select x).Count();
我不知道我在这里做错了什么。请帮忙。
.GetType
并查看创建的类型是什么。 - JaredParstring ty = t.Rows[0]["userid"].GetType().ToString();
它显示"System.UInt32" - user2168042UInt32
,与Int32
不同。在Field<T>
调用中使用UInt32
,它应该可以正常工作。 - JaredPar