Reputation: 13931
I have DataTable object that is filled with numeric data from my database. I have to handle all possible numeric-like data types (int32, int64, float, even datetime, but that last is not necessary).
I have to normalize all data in columns, each column separately, so I need to find maximum and minimum values for each column to calculate normalization coefficient.
Do I have to iterate "manually" through all rows to find these max and min values?
Some background:
I don't want to do this in SQL, because its kind of scientific application, where user works in SQL language and writes very complicated SQL queries. I don't want to force user to write even more complicated queries to get normalized data or get min/max values
Colums are fully dynamic, they depend on SQL query written by user.
Upvotes: 2
Views: 6588
Reputation: 324
This worked fine for me
int max = Convert.ToInt32(datatable_name.AsEnumerable()
.Max(row => row["column_Name"]));
Upvotes: 0
Reputation: 9862
You can do it by using DataTable.Select()
as :
DataRow [] dr = dataTable.Select("ID= MAX(ID)");
if(dr !=null)
{
// Console.WriteLine(dr[0]["ID"]);
int maxVal=Convert.ToInt32(dr[0]["ID"]);
}
Upvotes: 1
Reputation: 408
You can also use
Convert.ToInt32(datatable.Compute("min(columnname)", string.Empty));
Convert.ToInt32(datatable.Compute("max(columnname)", string.Empty));
Upvotes: 1
Reputation: 460138
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"));
int maxVal = (int)table.Compute("Max(ColName)", "");
Upvotes: 3
Reputation: 13706
Try this:
var min = myTable.AsEnumerable().Min(x => (int)x["column"]);
var max = myTable.AsEnumerable().Max(x => (int)x["column"]);
You'll need to make sure you have a reference to System.Data.DataSetExtensions
, which is not added to new projects by default.
Upvotes: 1