# 查找最大值小於另一個值的項目

class SurveyData（）{ 雙md; 雙tvd; } </代碼>

我有一個已經按升序排序的值列表。我想找到並返回列表中對象的索引，其最大tvd值小於或等於double。我怎樣才能有效地完成這項任務？

## 最佳答案

var maxCappedValue = values.TakeUntil(data => data.Tvd >= limit)
.LastOrDefault();


var maxCappedPair = values.Select((value, index) => new { value, index })
.TakeUntil(pair => pair.value.Tvd >= limit)
.LastOrDefault();


Of course, it would be more efficient to use a binary search - but also slightly more complicated. You could create a "dummy" value with the limit TVD, then use List.BinarySearch(dummy, comparer) where comparer would be an implementation of IComparer which compared by TVD. You'd then need to check whether the return value was non-negative (exact match found) or negative (exact match not found, return value is complement of where it would be inserted).