The most efficient way to do this (believe it or not) is to make two variables and write a for
loop.
another way of doing this is
int minLavel = Convert.ToInt32(dt.Select("AccountLevel=min(AccountLevel)")[0][0]);
I am not sure on the performace part but this does give the correct output
Session["MinDate"] = dtRecord.Compute("Min(AccountLevel)", string.Empty);
Session["MaxDate"] = dtRecord.Compute("Max(AccountLevel)", string.Empty);
Performance wise, this should be comparable. Use Select statement and Sort to get a list and then pick the first or last (depending on your sort order).
var col = dt.Select("AccountLevel", "AccountLevel ASC");
var min = col.First();
var max = col.Last();
This worked fine for me
int max = Convert.ToInt32(datatable_name.AsEnumerable()
.Max(row => row["column_Name"]));
var answer = accountTable.Aggregate(new { Min = int.MinValue, Max = int.MaxValue },
(a, b) => new { Min = Math.Min(a.Min, b.Field<int>("AccountLevel")),
Max = Math.Max(a.Max, b.Field<int>("AccountLevel")) });
int min = answer.Min;
int max = answer.Max;
1 iteration, linq style :)
Easiar approach on datatable could be:
int minLavel = Convert.ToInt32(dt.Compute("min([AccountLevel])", string.Empty));
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.
I don't know how my solution compares performance wise to previous answers.
I understand that the initial question was: What is the fastest way to get min and max values in a DataTable object, this may be one way of doing it:
DataView view = table.DefaultView;
view.Sort = "AccountLevel";
DataTable sortedTable = view.ToTable();
int min = sortedTable.Rows[0].Field<int>("AccountLevel");
int max = sortedTable.Rows[sortedTable.Rows.Count-1].Field<int>("AccountLevel");
It's an easy way of achieving the same result without looping. But performance will need to be compared with previous answers. Thought I love Cylon Cats answer most.
var min = dt.AsEnumerable().Min(row => row["AccountLevel"]);
var max = dt.AsEnumerable().Max(row => row["AccountLevel"]);
Source: Stackoverflow.com