The LINQ method is used here:
var list = new[] { 12, 15, 23, 94, 35, 48 }; var input = 17; var diffList = from number in list select new { number, difference = Math.Abs(number - input) }; var result = (from diffItem in diffList orderby diffItem.difference select diffItem).First().number;
EDIT : renamed some of the variables so that the code is less confusing ...
EDIT
The list variable is an implicit declaration of an int array. The first LINQ diffList defines an anonymous type with the source number from the list ( number ), as well as the difference between it and your current value ( input ).
The second LINQ result statement orders the collection of the anonymous type by difference, which is your rounding requirement. It takes the first item in this list, as it will have the smallest difference, and then selects only the original .number from the anonymous type.
source share