You can use LINQ
to get the lowest value without your cumbersome loop.
var lowest = dtRep.AsEnumerable()
.Where(r=> r.Field<Decimal>(col) > 0)
.Min(r => r.Field<Decimal>(col));
If you're using .NET 2.0 or lower, you could use DataTable.Compute:
lowest = System.Convert.ToDecimal(dtRep.Compute("MIN(ColName)", "ColName > 0"));
Edit: As mentioned in a comment to my answer, you're also iterating all DataColumns of the DataTable, hence the column-names are dynamic.
Try this approach which loops all columns, checks if the column's DataType is "numeric" and detects the lowest value of all rows in all columns:
var numericTypes =
new [] { typeof(Byte), typeof(Decimal), typeof(Double),
typeof(Int16), typeof(Int32), typeof(Int64), typeof(SByte),
typeof(Single), typeof(UInt16), typeof(UInt32), typeof(UInt64)};
Decimal lowest=Decimal.MaxValue;
foreach(DataColumn col in dtRep.Columns) {
if(numericTypes.Contains(col.DataType)){
var exp=string.Format("MIN({0})" , col.ColumnName);
var filter=string.Format("{0} > 0", col.ColumnName);
var d = Convert.ToDecimal(dtRep.Compute(exp, filter));
if(d < lowest) lowest = d;
}
}
Note: Exclude the typecheck if you know that all columns are numeric or that they contain strings which can be converted to decimals. (DataTable.Compute
will not throw an error if the DataColumn's DataType
is a String, but Convert.ToDecimal
will if the string is not convertible)
Finally: Here's the "bruteforce" way, iterating all values in the DataTable
and trying to parse them to a Decimal:
foreach(DataRow row in dtRep.Rows){
foreach(Object value in row.ItemArray) {
try {
Decimal d = Convert.ToDecimal(value);
if(d > 0 && d < lowest) lowest = d;
} catch(Exception ex) { }
}
}