Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Field<T> with Type?

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;
    }
like image 273
O.O Avatar asked Sep 12 '11 16:09

O.O


1 Answers

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);
like image 108
Jamie Dixon Avatar answered Sep 19 '22 23:09

Jamie Dixon