Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select min and max values of a column in a datatable?

For the following datatable column, what is the fastest way to get the min and max values?

AccountLevel   0   1   2   3  
like image 434
Ahmed Atia Avatar asked Mar 14 '10 14:03

Ahmed Atia


2 Answers

Easiar approach on datatable could be:

int minLavel = Convert.ToInt32(dt.Compute("min([AccountLevel])", string.Empty)); 
like image 175
Lalit Avatar answered Oct 01 '22 08:10

Lalit


int minAccountLevel = int.MaxValue; int maxAccountLevel = int.MinValue; foreach (DataRow dr in table.Rows) {     int accountLevel = dr.Field<int>("AccountLevel");     minAccountLevel = Math.Min(minAccountLevel, accountLevel);     maxAccountLevel = Math.Max(maxAccountLevel, accountLevel); } 

Yes, this really is the fastest way. Using the Linq Min and Max extensions will always be slower because you have to iterate twice. You could potentially use Linq Aggregate, but the syntax isn't going to be much prettier than this already is.

like image 40
Aaronaught Avatar answered Oct 01 '22 10:10

Aaronaught