且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用C#在数据表中找到最小和最大值

更新时间:2023-02-10 11:52:32

您可以随时在 DataTable 上使用 .Select 行:

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

这将返回一个 DataRow [] - 但是它通常只包含一行(除非您有多行具有相同的最大值)。



最小值相同:

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

请参阅 MSDN文档 DataTable.Select 了解更多详细信息。 p>

Possible Duplicate:
How to select min and max values of a column in a datatable?

I am searching for code that could find the min and max (or first and last values) from a column in a datatable.

I have stored the datatable with four column values I want to find the min and max values from the third column(index 2) and display it to the user.

I tried many ways but all are causing exceptions...

Last i tried this code but even this is not working..

count = Convert.ToInt32(dt.Rows.Count);

start = Convert.ToInt32(dt.Rows[0][2].ToString());

end = Convert.ToInt32(dt.Rows[count-1][2].ToString());

thanks vince

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.