How to Select Min and Max Values of a Column in a Datatable

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

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.

Find the min/max value in a column of a DataTable with Where clause?

I'm not sure whether you can do it in one statement, but you can do it in two using LINQ:

var minValue = tst.Where(t => t.Year == 2015).Min(t => t.Day1);
var maxValue = tst.Where(t => t.Year == 2015).Max(t => t.Day1);

tst needs to be something that LINQ recognises like a List, IEnumerable or Array.

You can use the Select method to get an array from the DataTable, and even do the first filter:

var data = tst.Select("Year = 2015", "Day1 ASC").ToList(); // Not that you need it sorted
var minValue = data.Min(t => t.Day1);
var maxValue = data.Max(t => t.Day1);

How to find max value of a column in a datatable?

Your field ROWNUM is of type decimal and you are trying to cast it to string, that is why you are getting the error.

It should be:

r.Field<decimal>("ROWNUM").ToString()

Not really sure why you are converting to Boolean and parsing an int to int again.

Your query should be:

var maxVal = dsloadReferralCodes.Tables["dtReferralCodesTable"]
.AsEnumerable()
.Max(r => r.Field<decimal>("ROWNUM"));

How to get the highest value from a datatable?

Haven't tried it myself but probably something along:

var highestVersion = (from row in dt.AsEnumerable()
where row.Field<string>("id") == class.ID
select row.Field<double>("verlabel")).Max();

C# DataTable Min and Max of each row ( not each column) dynamically

Here's a very small and stupid example that illustrates how you can use the RowChanged handler to do the calculations.
This might give you other problems if you use complex dataset/datatable/dataview functionality, but if you mainly use one datatable in one datagridview I think this might work.

class GridForm : Form
{
private DataTable _table = new DataTable();
private DataGridView _grid = new DataGridView();

public GridForm()
{
_table.Columns.Add("Col1", typeof(double));
_table.Columns.Add("Col2", typeof(double));
_table.Columns.Add("Col3", typeof(double));
_table.Columns.Add("Col4", typeof(double));

var calcCol = _table.Columns.Add("Calc", typeof(double));
calcCol.DefaultValue = 0.0d;
_table.RowChanged += (sender, args) =>
{

// 4 first columns as doubles
var vals = args.Row.ItemArray.Take(4).Cast<double>().ToArray();
var calc = vals.Max() - vals.Min();

// Only set if changed to avoid infinite loop
if (!double.Equals(args.Row["Calc"], calc))
{
args.Row["Calc"] = calc;
}
};

_table.LoadDataRow(new object[] {
1d, 1d, 3d, 4d
}, true);
_table.LoadDataRow(new object[] {
2d, 2d, 5d, 6d
}, true);

Controls.Add(_grid);
_grid.DataSource = _table;
_grid.Columns["Calc"].ReadOnly = true;
_grid.Dock = DockStyle.Fill;
_grid.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
_grid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
_grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}
}

Get the highest value from a given column in a datatable

If You want to get highest Value from DataTable in code not in sql, then You can just use linq like below:

int highestNumber = dtApprovalNumber.AsEnumerable().Max(x => x.Field<int>("SomeIntegerColumn");

EDIT.

According to Your comment - if You want to calculate max value from a string column which holds numbers(don't get it why) You can go with something like that:

int highestNumber = dtApprovalNumber.AsEnumerable().Max(x => int.Parse(x.Field<string>("SomeStringColumn")));

Please Note that if any of those string values is not convertable it will fail then You will have to do it other way.

EDIT.2

Since I've just tried it I'll share with You - the situation when You have string Column and You are not sure if all of them are convertable(for example some might be empty). See below:

int tempVariable;
int highestNumber = dt.AsEnumerable()
.Where(x => int.TryParse(x.Field<string>("SomeColumn"), out tempVariable))
.Max(m => int.Parse(m.Field<string>("SomeColumn")));

Maximum value in datatable column c#

The problem is that you have created string columns but you want to get the max-values according to their numeric value. The best way is to store the corrrect type in the first place. Then you could either use DataTable.Compute or Linq-To-DataSet:

create an int column:

 curriculmDataTable.Columns.Add("Id", typeof(int));

convert the strings to int and add them to the table:

foreach(string line in File.ReadLines(filePath))
{
DataRow row = curriculmDataTable.Rows.Add();
string[] fields = line.Split(new[]{(char)9});
int id;
if(fields.Length == 3 && int.TryParse(fields[0], out id)
{
row.SetField("Id", id);
row.SetField("Course", fields[1]);
row.SetField("Credit", fields[2]);
}
}

Now you can use Linq:

int maxID = curriculmDataTable.AsEnumerable().Max(r => r.Field<int>("Id"));

DataTable.Compute (works also with earlier .NET versions):

int maxID = (int)curriculmDataTable.Compute("Max(Id)", "")

Processing data in DataTable - how to find minimum and maximum for each column?

Do I have to iterate "manually" through all rows to find these max and
min values?

Define manually. Yes, you have to calculate the Min and Max values by enumerating all DataRows. But that can be done either with the old DataTable.Compute method or with

Linq:

int minVal = table.AsEnumerable().Min(r => r.Field<int>("ColName"));
int maxVal = table.AsEnumerable().Max(r => r.Field<int>("ColName"));

DataTable.Compute:

int maxVal = (int)table.Compute("Max(ColName)", "");


Related Topics



Leave a reply



Submit