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
Solution 1:
Easiar approach on datatable could be:
int minLavel = Convert.ToInt32(dt.Compute("min([AccountLevel])", string.Empty));
Solution 2:
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.
Solution 3:
Use LINQ. It works just fine on datatables, as long as you convert the rows collection to an IEnumerable.
List<int> levels = AccountTable.AsEnumerable().Select(al => al.Field<int>("AccountLevel")).Distinct().ToList();
int min = levels.Min();
int max = levels.Max();
Edited to fix syntax; it's tricky when using LINQ on DataTables, and aggregating functions are fun, too.
Yes, it can be done with one query, but you will need to generate a list of results, then use .Min() and .Max() as aggregating functions in separate statements.
Solution 4:
This worked fine for me
int max = Convert.ToInt32(datatable_name.AsEnumerable()
.Max(row => row["column_Name"]));
Solution 5:
The most efficient way to do this (believe it or not) is to make two variables and write a for
loop.