使用C#在数据表中找到最小和最大值 [英] find min and max values in a datatable using C#

查看:347
本文介绍了使用C#在数据表中找到最小和最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何在数据表中选择列的最小值和最大值?






我正在搜索可以从数据表中的列中找到最小值和最大值(或第一个和最后一个值)的代码。



我已经使用四列值存储了datatable,我想从第三列(索引2)中找到最小值和最大值,并将其显示给用户。



我尝试了很多方法,但都是引起异常...



最后我试过这个代码,但即使这样也不行。 / p>

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

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

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

感谢
vince

解决方案

您可以随时在 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.

这篇关于使用C#在数据表中找到最小和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆