简体   繁体   中英

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? 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. Firstly, I found that the data in my datatable was of type string so converted the value to double and determine the maximum value. 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 .

You cannot cast directly from a boxed float to a double , so you need an extra cast.

It would be better to use the actual type of your field from the dataset, or to change that type to 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):

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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