Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get maximum closest number from int list

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading