简体   繁体   中英

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.

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

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.

You can also use

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

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

This worked fine for me

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM