find min and max values in a datatable using C# [duplicate]

依然范特西╮ 提交于 2019-12-04 06:57:52

You could always use the .Select method on the DataTable to get those rows:

var maxRow = dt.Select("ID = MAX(ID)");

This will return a DataRow[] array - but it should typically only contain a single row (unless you have multiple rows with the same, maximum value).

Same goes for the minimum:

var minRow = dt.Select("ID = MIN(ID)");

See the MSDN docs on DataTable.Select for more details.

Swapnil

Answer is available on stackoverflow : How to select min and max values of a column in a datatable?

Thanks, Swapnil.

What datatype are count start and end declared as? That isn't shown in your code.

Also, the code you've provided, if working, would only give you the first and last element, NOT the minimum in the set and the maximum in the set. If you are looking for min/max, you'd need to write a loop, such as this:

// minimum
int min = dt.Rows[0][2]; // assuming you want the third column (index 2)
for(int i = 1; i < dt.Rows.Count; i++) 
{
    if(min > (int)dt.Rows[i][2]) min = (int)dt.Rows[i][2];
}

// maximum
int max = dt.Rows[0][2]; // assuming you want the third column (index 2)
for(int i = 1; i < dt.Rows.Count; i++) 
{
    if(max < (int)dt.Rows[i][2]) max = (int)dt.Rows[i][2];
}

Obviously these can also be combined into a single loop:

// minimum and maximum
int max = dt.Rows[0][2]; // assuming you want the third column (index 2)
int min = dt.Rows[0][2]; // assuming you want the third column (index 2)
for(int i = 1; i < dt.Rows.Count; i++) 
{
    if(max < (int)dt.Rows[i][2]) max = (int)dt.Rows[i][2];
    if(min > (int)dt.Rows[i][2]) min = (int)dt.Rows[i][2];
}

@marc_s' answer is more elegant for your specific use case (data table), but mine will work for any data set in an indexed collection.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!