LINQ to Get Closest Value?

前端 未结 4 529
独厮守ぢ
独厮守ぢ 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 06:46

    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)
        .First().n;
    

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

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

提交回复
热议问题