简体   繁体   English

在DataTable中处理数据-如何查找每列的最大值和最小值?

[英]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. 我有DataTable对象,该对象充满了数据库中的数字数据。 I have to handle all possible numeric-like data types (int32, int64, float, even datetime, but that last is not necessary). 我必须处理所有可能的类似数字的数据类型(int32,int64,float甚至datetime,但最后那是没有必要的)。

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. 我不想在SQL中执行此操作,因为它是一种科学应用程序,用户可以使用SQL语言工作并编写非常复杂的SQL查询。 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. 列是完全动态的,它们依赖于用户编写的SQL查询。

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 . 是的,您必须通过枚举所有DataRows来计算MinMax值。 But that can be done either with the old DataTable.Compute method or with 但这可以通过旧的DataTable.Compute方法或通过

Linq : Linq

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

DataTable.Compute : 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. 您需要确保对System.Data.DataSetExtensions的引用在默认情况下不会添加到新项目中。

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 : 您可以使用DataTable.Select()作为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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