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.

Rufus L
  • 36,127
  • 5
  • 30
  • 43
Owais Ahmed
  • 1,364
  • 1
  • 30
  • 62

1 Answers1

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}

Rufus L
  • 36,127
  • 5
  • 30
  • 43
Misiakw
  • 902
  • 8
  • 28
  • 2
    And, if you want _"The Price Is Right"_ rules (closest without going over), all you have to change is the lambda. – Flydog57 Feb 05 '19 at 23:37
  • 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} – Owais Ahmed Feb 05 '19 at 23:42
  • @OwaisAhmed: Fiddle with the lambda expression to get it right. – Flydog57 Feb 05 '19 at 23:45
  • my fault, invalid order. here tested solution (i'll edit this one) https://dotnetfiddle.net/Boolsn – Misiakw Feb 05 '19 at 23:50
  • @Flydog57 sorry what do you mean by that – Owais Ahmed Feb 05 '19 at 23:50
  • It should be `OrderBy` if you want to get the closest values. `OrderByDescending` will put the items with the ***largest*** difference first. – Rufus L Feb 06 '19 at 00:45