开发者

using LINQ getting previous and next element

One of my colleague was looking for something like picking up previous and next values from a list for a given value. I wrote a little function with some help of Google, which works but I wanted to see 1. if is this an efficient way to do this? 2. Any other way in LINQ to do this?

    private static List<double> GetHighLow(double value)
    {
        List<double> tenorList = new List<double> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 20, 30 };

        double previous = tenorList.OrderByDescending(s => s).Where(s => s.CompareTo(value) < 0).FirstOrDefault(); 
        double next = tenorList.OrderBy(s => s).Where(s => s.CompareTo(开发者_Python百科value) > 0).FirstOrDefault();

        List<double> values = new List<double> { previous, next };
        return values;
    }

thanks Pak


Ordering just to find a single item would make me suspicious. You can do it in linear time this way:

double prev = double.MinValue;
double nx = double.MaxValue;
foreach (var item in tenorList) {
    if (item < value && item > prev) { prev = item; }
    if (item > value && item < nx) { nx = item; }
}

List<double> values = new List<double> { prev, nx };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜