我想编写一个函数“getCount”来从数据表中为不同的用户名返回 int 的结果,如下所示:
static void Main(string[] args)
{
DataTable table = new DataTable();
table.Columns.Add("username", typeof(string));
table.Columns.Add("count", typeof(int));
table.Columns.Add("code", typeof(string));
table.Rows.Add("Peter", 300, "wer");
table.Rows.Add("Peter", 299, "sdf");
table.Rows.Add("Peter", 298, "34d");
table.Rows.Add("Peter", 297, "4ed");
table.Rows.Add("Paul", 200, "1vc");
table.Rows.Add("Paul", 200, "64f");
table.Rows.Add("Paul", 200, "45d");
table.Rows.Add("Paul", 200, "dcd");
//expectedly 300, i.e. the first row of count column for peter
int x1 = getCount(table, "Peter");
//expectedly 200, i.e. the first row of count column for paul
int x2 = getCount(table, "Paul");
}
static int getCount(DataTable dt, string name)
{
var query = dt.AsEnumerable().Where(p => p.Field<string>("username") == name)
.Select(p => p.Field<string>("count")).Take(1);
return Convert.ToInt32(query); //error here
}
但是在 Convert 语句中出现错误:
无法将“d__3a`1[System.String]”类型的对象转换为“System.IConvertible”类型。
问题是什么?谢谢