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.
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With