2 回答
TA贡献1909条经验 获得超7个赞
如果你可以使用List<int>而不是数组,它会让事情更容易编码,并且可能更清洁,这取决于你问的是谁。
假设你改变了这一点:
int[] array = new int[10] {g1,g2,g3,g4,g5,g6,g7,g8,g9,g10};
变成这样的列表:
List<int> values = new List<int>(){g1,g2,g3,g4,g5,g6,g7,g8,g9,g10};
聚合将测试每个元素,直到完全测试列表。所以我们可以尝试像这样获得最接近和最远的值
// value you want to check is the average of the list.
// Average is already implemented for the List
var value = values.Average();
// will keep the closest value in the collection to our value we are looking for
// and keep testing with the following value to end up with the final closest
var closestTo = values.Aggregate((x, y) => Math.Abs(x - value) < Math.Abs(y - value) ? x : y);
// same logic as closest except we keep the furthest
var furthestTo = values.Aggregate((x, y) => Math.Abs(x - value) > Math.Abs(y - value) ? x : y);
- 2 回答
- 0 关注
- 1372 浏览
添加回答
举报