在給定正整數集合中查詢最靠近輸入值右側的項
阿新 • • 發佈:2019-02-13
For迴圈:
/// <summary> /// 獲取列表中最靠近給定數值的右側數位置(多執行緒) /// </summary> private int GetNearestRightNumInList(List<int> _list, int _num) { int index = -1; int _right = int.MaxValue; System.Threading.Tasks.Parallel.For(0, _list.Count, (_n) => { if (_num <= _list[_n]) { if (_list[_n] < _right) { _right = _list[_n]; index = _n; } } }); return index; }
ForEach迴圈:
ForEach 是比 For 要快的/// <summary> /// 獲取列表中最靠近給定數值的右側的值(多執行緒) /// </summary> private int GetNearestRightNumInList(List<int> _list, int _num) { int _right = int.MaxValue; Parallel.ForEach(_list, _n => { if (_num <= _n) { if (_n < _right) { _right = _n; } } }); return _right > _list.Last() ? -1 : _right; }