Kamil
Kamil

Reputation: 13931

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

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

Answers (5)

Animesh Anand
Animesh Anand

Reputation: 324

This worked fine for me

int  max = Convert.ToInt32(datatable_name.AsEnumerable()
                        .Max(row => row["column_Name"]));

Upvotes: 0

Mohammad Arshad Alam
Mohammad Arshad Alam

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

Tralli
Tralli

Reputation: 408

You can also use

Convert.ToInt32(datatable.Compute("min(columnname)", string.Empty));
Convert.ToInt32(datatable.Compute("max(columnname)", string.Empty));

Upvotes: 1

Tim Schmelter
Tim Schmelter

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"));

DataTable.Compute:

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

Upvotes: 3

Bobson
Bobson

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

Related Questions