我正在寻找一种通过LINQ实现这一目的的有效方法:
我有一个值列表,例如{98,98.5,99,99.5,100,101,102}
我想提供一个参考值,然后找到之前和之后最接近的值是相等的距离。
实施例1)参考值为99->我想找到98.5和99.5
实施例2)参考值为100 - >我想找到99和101(注意,它正在跳过99.5)
如果除参考值之外没有2个相等距离的值,则它应返回null
答案 0 :(得分:4)
var items = new[] {98, 98.5, 99, 99.5, 100, 101, 102};
var target = 99;
var result = items.Distinct() // Omit duplicates.
.Select(Value => new {Value, Distance = Math.Abs(target - Value)}) // pair the Value with the distance.
.GroupBy(x => x.Distance) // Group the values by distance.
.Where(x => x.Count() > 1) // Omit the values where there is no symmetrical distance.
.OrderBy(x => x.Key) // Order them by distance.
.FirstOrDefault(); // Take the first one.
if (result != null)
foreach (var item in result)
Console.WriteLine(item.Value);