如何在Linq中使用像Count(),Max()这样的聚合函数选择值?
问题描述:
using (School_365Entities db = new School_365Entities())
{
var Query = (from x in db.tbl_staticfielddetails
where x.institutionid == insid
select x.id).Count();
foreach (var item in Query)
{
cnt = Convert.ToInt32(item.ToString());
}
}
b $ b
我收到错误
I got the error
Error foreach statement cannot operate on variables of type 'int' because 'int' does not contain a public definition for 'GetEnumerator'
答
1.上面的代码只返回一个整数类型的结果(计数结果),你不能迭代成一个。
2.使用几乎所有可能的聚合函数的LINQ表达式的示例ee下一个MSDN链接:
http://code.msdn.microsoft。 com / LINQ-Aggregate-Operators-c51b3869 [ ^ ]
1.Your code above return only one results of type integer (the count result) and you cannot iterate into one it.
2.For examples of LINQ expresions that are using almost all possible aggregate functions see the next MSDN link:
http://code.msdn.microsoft.com/LINQ-Aggregate-Operators-c51b3869[^]
这可能对你有所帮助......
http://www.c-sharpcorner.com/UploadFile/3d39b4/aggregate-functions-in-linq- to-sql / [ ^ ]
this might help you...
http://www.c-sharpcorner.com/UploadFile/3d39b4/aggregate-functions-in-linq-to-sql/[^]
您可以直接获取如下计数
you can directly get the count as below
int count = (from x in db.tbl_staticfielddetails
where x.institutionid == insid
select x.id).Count();
reason is Count [^] method return type is int