I have a method that determines the min and max of a column in a DataTable
:
public void GetMinMaxRange( DataTable data, string valueColumnName )
{
var min = data.AsEnumerable().Min(m => m.Field<double>(valueColumnName));
var max = data.AsEnumerable().Max(m => m.Field<double>(valueColumnName));
}
I want to refactor this to be:
public void GetMinMaxRange( DataTable data, string valueColumnName )
{
DataColumn column = data.Columns[valueColumnName];
var min = data.AsEnumerable().Min(m => m.Field<column.DataType>(valueColumnName));
var max = data.AsEnumerable().Max(m => m.Field<column.DataType>(valueColumnName));
}
I need to determine the datatype and use it instead of hard-coding m.Field<double>
. How to do this?
UPDATE As to why I want to calculate the difference between the min and the max
public static double/decimal/int GetMinMaxRange<T>(DataTable data,
string valueColumnName) where T : IComparable<T>
{
DataColumn column = data.Columns[valueColumnName];
var min = data.AsEnumerable().Min(m => m.Field<T>(valueColumnName));
var max = data.AsEnumerable().Max(m => m.Field<T>(valueColumnName)); ;
return max - min;
}
Simply creating this as a generic should work:
public void GetMinMaxRange<T>( DataTable data, string valueColumnName )
where T : IComparable<T>
{
DataColumn column = data.Columns[valueColumnName];
var min = data.AsEnumerable().Min(m => m.Field<T>(valueColumnName));
var max = data.AsEnumerable().Max(m => m.Field<T>(valueColumnName));
}
Which you would then use as:
GetMinMaxRange<MyType>(dataTable, valueColumnName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With