C# 如何在数据表中查找列的最大值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16009628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find max value of a column in a datatable?
提问by user545359
I am trying to find the max value of a column in a datatable. Below is my code
我试图在数据表中找到列的最大值。下面是我的代码
var maxVal = dsloadReferralCodes.Tables["dtReferralCodesTable"].AsEnumerable().Max(r => Convert.ToBoolean(int.TryParse(r.Field<string>("ROWNUM"), out intROWNUM)) ? (int?)intROWNUM : null);
and below id the error i am getting while trying to get the max value and assigning it to intROWNUM
下面是我在尝试获取最大值并将其分配给 intROWNUM 时遇到的错误
Unable to cast object of type 'System.Decimal' to type 'System.String'
无法将“System.Decimal”类型的对象转换为“System.String”类型
Can someone help me in resolving the issue. This has been troubling me since long. Thanks in advance...
有人可以帮助我解决问题。这一直困扰着我很久。提前致谢...
采纳答案by Habib
Your field ROWNUMis of type decimal and you are trying to cast it to string, that is why you are getting the error.
您的字段ROWNUM是十进制类型,您正试图将其转换为字符串,这就是您收到错误的原因。
It should be:
它应该是:
r.Field<decimal>("ROWNUM").ToString()
r.Field<decimal>("ROWNUM").ToString()
Not really sure why you are converting to Boolean and parsing an int to int again.
不太确定为什么要转换为 Boolean 并再次将 int 解析为 int。
Your query should be:
您的查询应该是:
var maxVal = dsloadReferralCodes.Tables["dtReferralCodesTable"]
.AsEnumerable()
.Max(r => r.Field<decimal>("ROWNUM"));
回答by Arshad
you can get it in simple manner with DataTable.Select():
您可以使用DataTable.Select()以简单的方式获得它:
DataRow [] dr = dsloadReferralCodes.Tables["dtReferralCodesTable"].Select("ROWNUM= MAX(ROWNUM)");
if(dr !=null)
{
// Console.WriteLine(dr[0]["RowNum"]);
int maxVal=Convert.ToInt32(dr[0]["RowNum"]);
}
回答by tintin
What about:
关于什么:
maxVal = (decimal) dsloadReferralCodes.Tables["dtReferralCodesTable"].Compute( "Min(ROWNUM)", string.Empty );
(this doesn't use LINQ, so it would also work for .net 2.0)
(这不使用 LINQ,所以它也适用于 .net 2.0)

