对于下面的数据表列,什么是让最小值和最大值的最快方法?
AccountLevel
0
1
2
3
解决方案
INT minAccountLevel = int.MaxValue;
INT maxAccountLevel = int.MinValue;
的foreach(在table.Rows的DataRow博士)
{
INT accountLevel = dr.Field< INT>(AccountLevel);
minAccountLevel = Math.Min(minAccountLevel,accountLevel);
maxAccountLevel = Math.Max(maxAccountLevel,accountLevel);
}
是的,这的确是最快的方法。用LINQ 最小
和最大
扩展将永远是慢,因为你必须重复两次。你可能使用Linq 总结
,但语法是不会有太大prettier比这已经是了。
For the following datatable column, what is the fastest way to get the min and max values?
AccountLevel
0
1
2
3
解决方案
int minAccountLevel = int.MaxValue;
int maxAccountLevel = int.MinValue;
foreach (DataRow dr in table.Rows)
{
int accountLevel = dr.Field<int>("AccountLevel");
minAccountLevel = Math.Min(minAccountLevel, accountLevel);
maxAccountLevel = Math.Max(maxAccountLevel, accountLevel);
}
Yes, this really is the fastest way. Using the Linq Min
and Max
extensions will always be slower because you have to iterate twice. You could potentially use Linq Aggregate
, but the syntax isn't going to be much prettier than this already is.