2

I am developing an asp.net application where i have a dataset having 3 tables i.e. ds.Tables[0], Tables[1] and Tables[2]

I need to find minimum number and maximum number out of all the 3 tables of dataset. How to do that?

I found similar question in SO here but not sure how that would help me getting my way?

UPDATED:

 double minValue = double.MinValue;
 double maxValue = double.MaxValue;
 foreach (DataRow dr in dtSMPS.Rows)
 {
            double actualValue = dr.Field<double>("TOTAL_SUM");  // This fails specifying type cast error
            minValue = Math.Min(minValue, actualValue);
            maxValue = Math.Max(maxValue, actualValue);
 }

Please guide! Thanks.

Community
  • 1
  • 1
xorpower
  • 17,975
  • 51
  • 129
  • 180

3 Answers3

1

You could use an extra for loop added to the solution you have already linked to. I.e.

int minAccountLevel = int.MaxValue;
int maxAccountLevel = int.MinValue;

for (int i = 0; i < 3; i++)
{
var table = ds.Tables[i];
foreach (DataRow dr in table.Rows)
{
    int accountLevel = dr.Field<int>("AccountLevel");
    minAccountLevel = Math.Min(minAccountLevel, accountLevel);
    maxAccountLevel = Math.Max(maxAccountLevel, accountLevel);
}
}
Balthy
  • 866
  • 6
  • 3
  • thanks for the input.As mentioned in one of my comments that datatype of my column is decimal. Hence i am changing the datatype to decimal but the code fails. – xorpower Oct 06 '11 at 13:47
  • Is it nullable? Try checking if dr["column"] == DBNull.Value and you can try using Convert.ToDecimal(dr["column"]) if it is not null. – Balthy Oct 06 '11 at 13:54
1

If they have the same column name suppose 'decimalValue' then:

decimal minAccountLevel = decimal.zero;
decimal maxAccountLevel = decimal.zero;
for (int i = 0; i < dts.Tables.Count; i++)
        {
            foreach (DataRow dr in dts.Tables[i].Rows)
            {
                decimal accountLevel = decimal.Parse(dr["decimalValue"].ToString());
                minAccountLevel = Math.Min(minAccountLevel, accountLevel);
                maxAccountLevel = Math.Max(maxAccountLevel, accountLevel);
            }
        }
Boomer
  • 1,468
  • 1
  • 15
  • 19
1

you can select the min and max for each DataTable using the Compute method on each DataTable.

Disclaimer this is not safe code; you should check for errors, nulls, and make it more readable.

Something like this should work:

decimal max = Math.Max(Convert.ToDecimal(ds.Tables[2].Compute("MAX(AccountLevel)","").ToString()),  Math.Max(Convert.ToDecimal(ds.Tables[0].Compute("Max(AccountLevel)","").ToString()),Convert.ToDecimal(ds.Tables[1].Compute("Max(AccountLevel)","").ToString()));
Icarus
  • 63,293
  • 14
  • 100
  • 115