1. 程式人生 > >在給定正整數集合中查詢最靠近輸入值右側的項

在給定正整數集合中查詢最靠近輸入值右側的項

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迴圈:

        /// <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;
        }
ForEach 是比 For 要快的