Home > Software design >  Get maximum closest number from int list
Get maximum closest number from int list

Time:12-13

I have number list like below and I should check a condition to get most suitable match.

List<int> numbers= new List<int>();
numbers.Add(1000);
numbers.Add(3000);
numbers.Add(5500);
numbers.Add(7000);

If I send a value to check it should check like below examples

Scenario 1: If I send a value less than or equal 1000 to check, it should return 1000

Scenario 2: If I send a value between 1001 - 3000 to check, it should return 3000

Scenario 3: If I send a value between 3001 - 5500 to check, it should return 5500

Scenario 4: If I send a value between 5501 - 7000 to check, it should return 7000

Scenario 5: If I send a value above 7000 to check, it should return nothing.

Can I do this with Linq? or what is the most efficient way to do this?

Update: the numbers in maxCheckPoint is dynamic and it can be any values. So we cannot hard coded and check

CodePudding user response:

You can do this with LINQ:

int input = 1000;
int? result = numbers
    .OrderBy(n => n) // get the numbers in ascending order
    .SkipWhile(n => n < input) // skip until the remaining set >= input
    .Cast<int?>() // cast to nullable int
    .FirstOrDefault(); // take the first or default entry (if no items remain, it will be null)

CodePudding user response:

Well, it's too late and my solution is far away from perfect, but:

int number = 400; //imput number
        int closest = numbers.Aggregate((x, y) => Math.Abs(x - number) < Math.Abs(y - number) ? x : y); // searching the closer one           
        int compare;
        try{
         if (numbers.IndexOf(closest) != 0)
            {
                compare = Math.Max(closest, numbers[numbers.IndexOf(closest)   1]); // if it's not 0th and last
            }
            else
            { compare = closest; // if closest with index 0}
        }// check which closest number is bigger 
        catch{            
             compare = closest; // if closest is last
        }
Console.WriteLine(compare);
  • Related