LINQ to Get Closest Value?

前端 未结 4 518
独厮守ぢ
独厮守ぢ 2020-12-13 06:20

I have a List, MyStuff has a property of Type Float.

There are objects with property values of 10,20,22,30.

I need to write a query that finds the objects cl

4条回答
  •  醉梦人生
    2020-12-13 07:07

    Here's a solution that satisfies the second query in linear time:

    var pivot = 21f;
    var closestBelow = pivot - numbers.Where(n => n <= pivot)
                                      .Min(n => pivot - n);
    

    (Edited from 'above' to 'below' after clarification)

    As for the first query, it would be easiest to use MoreLinq's MinBy extension:

    var closest = numbers.MinBy(n => Math.Abs(pivot - n));
    

    It's also possible to do it in standard LINQ in linear time, but with 2 passes of the source:

    var minDistance = numbers.Min(n => Math.Abs(pivot - n));
    var closest = numbers.First(n => Math.Abs(pivot - n) == minDistance);
    

    If efficiency is not an issue, you could sort the sequence and pick the first value in O(n * log n) as others have posted.

提交回复
热议问题