C# linq list find closest numbers
Asked Answered
G

1

6

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.

Glick answered 5/2, 2019 at 23:32 Comment(0)
I
16

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}

Iatrics answered 5/2, 2019 at 23:36 Comment(6)
And, if you want "The Price Is Right" rules (closest without going over), all you have to change is the lambda.Hsining
yes i tied but not giving me the right results. I passed the list {20000,30000,40000,60000,80000,90000}. Expecting result :{20000,30000,40000,60000} what I am getting is {90000,80000,60000,40000}Glick
@OwaisAhmed: Fiddle with the lambda expression to get it right.Hsining
my fault, invalid order. here tested solution (i'll edit this one) dotnetfiddle.net/BoolsnIatrics
@Hsining sorry what do you mean by thatGlick
It should be OrderBy if you want to get the closest values. OrderByDescending will put the items with the largest difference first.Sarcastic

© 2022 - 2024 — McMap. All rights reserved.