简体   繁体   English

从c#中的数据表中获取最大值代码抛出InvalidCastException

[英]Get Maximum value code from a datatable in c# throws InvalidCastException

I have a datatable similar to 我有一个类似的数据表

Rank  Year  Value
1     1990  1234556.5676
2     2000  12313.1212 
3     2010  131242.1234

I have the following code which I wrote with the help of the following thread: How to select min and max values of a column in a datatable? 我在以下线程的帮助下编写了以下代码: 如何选择数据表中列的最小值和最大值?

double dMaxValue = 0;
foreach (DataRow dr in dsView.Tables[0].Rows)
{
    double dValue = dr.Field<double>("Value");
    dMaxValue = Math.Max(dMaxValue, dValue);
}

This is throwing an error "Specified cast is not valid". 这会引发错误“指定的强制转换无效”。 What am I missing here and also how can I get the value of the year column once I find the MAX Value? 我在这里缺少什么,以及在找到MAX值后如何获得年份列的值? The year needs to be returned to the calling program. 年份需要返回到调用程序。

EDIT- (SOLUTION): With the help of SLacks I figured out how to accomplish the task. 编辑 - (解决方案):在SLacks的帮助下,我想出了如何完成任务。 Firstly, I found that the data in my datatable was of type string so converted the value to double and determine the maximum value. 首先,我发现我的数据表中的数据是字符串类型,因此将值转换为double并确定最大值。 Then used a variable to find the corresponding year. 然后使用变量来查找相应的年份。

string sYear = string.Empty;
double dMaxValue = double.MinValue;
foreach (DataRow dr in dsView.Tables[0].Rows)
{
    double dValue = Convert.ToDouble(dr.Field<string>("Value"));
    if (dValue > dMaxValue)
    {
        sYear = dr["Year"].ToString();
    }
    dMaxValue = Math.Max(dMaxValue, dValue);                            
}
return sYear;

Your Value column is probably a decimal , or perhaps a float . 您的Value列可能是decimal ,也可能是float

You cannot cast directly from a boxed float to a double , so you need an extra cast. 你不能直接从盒装float投射到double ,所以你需要额外的施法。

It would be better to use the actual type of your field from the dataset, or to change that type to Double . 最好使用数据集中字段的实际类型,或将该类型更改为Double

How do you get the year? 你怎么得到这一年?

You can sort the dataview: 您可以对数据视图进行排序:

           http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx

and then pluck the year from the sorted view. 然后从排序视图中提取年份。

Try something like this (using System.Linq and Extensions, note the let variable for the conversion): 尝试这样的事情(使用System.Linq和Extensions,注意转换的let变量):

double maxVal = 0; // supposing all your values are > 0
var maxRow = (from row in dsView.Tables[0].AsEnumerable() 
   let Val = Convert.ToDouble(row.Field<string>("Value"))
   where Val > maxVal
   select new {maxVal = Val, Year = row.Field<int>("Year")}).Last();

return maxRow.Year;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM