xorpower
xorpower

Reputation: 18973

Found minimum and maximum value from dataset containing multiple tables

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.

Upvotes: 2

Views: 2480

Answers (3)

Icarus
Icarus

Reputation: 63966

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()));

Upvotes: 1

Boomer
Boomer

Reputation: 1478

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);
            }
        }

Upvotes: 1

Balthy
Balthy

Reputation: 906

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);
}
}

Upvotes: 1

Related Questions