Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Round to list values

Tags:

c#

.net

rounding

I'm trying to round a result value to the next number in a list.

If the value is (187) I need to set the result to (240)

int[] list = new int[] { 16, 25, 35, 50, 70, 95, 120, 150, 185, 240, 300, 400 };
double max;
max = list.Where(x => x <= result).Max();

But this does not work.

like image 692
Mohamed Ahmed Avatar asked Apr 24 '26 02:04

Mohamed Ahmed


2 Answers

You're close:

list.Where(x => x >= result).Min();
like image 132
D Stanley Avatar answered Apr 25 '26 18:04

D Stanley


You just want the first item greater than or equal to your expected result:

var max = list.FirstOrDefault(x => x >= result)

NOTE: This assumes the list is ordered, as your example seems to suggest.

If you want to get an exception if there's no match then just use First:

var max = list.First(x => x >= result)
like image 25
Sean Avatar answered Apr 25 '26 19:04

Sean