Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# linq list find closest numbers

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.

like image 662
Owais Ahmed Avatar asked Feb 05 '19 23:02

Owais Ahmed


People also ask

What C is used for?

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 ...

What is the full name of C?

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.

Is C language easy?

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 in C language?

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.


1 Answers

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}

like image 132
Misiakw Avatar answered Oct 01 '22 08:10

Misiakw