LINQ to Get Closest Value?

Try sorting them by the absolute value of the difference between the number and 21 and then take the first item:

float closest = MyStuff
    .Select (n => new { n, distance = Math.Abs (n - 21) })
    .OrderBy (p => p.distance)

Or shorten it according to @Yuriy Faktorovich’s comment:

float closest = MyStuff
    .OrderBy(n => Math.Abs(n - 21))

Leave a Comment