C# linq list find closest numbers

  • A+
Category:Languages

I have a list of numbers and I want to find closest four numbers to a search number.

For example if the search number is 400000 and the list is: {150000, 250000, 400000, 550000, 850000, 300000, 200000), then the closest 4 numbers would be:

{300000, 400000, 250000, 550000} 

Any help or suggestion would be appreciated.

 


You can use OrderBy to order the list by the absolute value of the difference between each item and your search term, so that the first item in the ordered list is closest to your number, and the last item is furthest from the number. Then you can use the Take extension method to take the number of items you need:

var list = new List<long> {150000, 250000, 400000, 550000, 850000, 300000, 200000}; var search = 400000; var result = list.OrderBy(x => Math.Abs(x - search)).Take(4); Console.WriteLine(string.Join(", ", result)); 

Output: {400000, 300000, 250000, 550000}

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: