Reputation: 7012
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;
Upvotes: 0
Views: 1331
Reputation: 153
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;
Upvotes: 0
Reputation: 5421
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.
Upvotes: 0
Reputation: 887469
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
.
Upvotes: 2