How to check if a decimal value from input is greater than a list of decimal

Viewed 573

I have a decimal list. I need to find if a decimal input is greater than any of the value present in the list.

Decimal threshold = 20;

List<Decimal> InputList = new List<Decimal>() { 10, 20, 35 };

Please note this input list might have one or more items in the list.

I want to check if one of the items is greater than the threshold value, then do something else.

2 Answers

You can use Any. It checks if at least one element in the list matches the condition.

InputList.Any(x => x > threshold);

If you are not familiar with Linq you could write a function like this:

private static bool CheckIfLarger(IEnumerable<double> list, double value){
  foreach(var item in list) if(value<=item) return false;    
  return true;
}

Edit: Explanation: you compare your value to every number in the List and if it is smaller you returne false, since than your number is not smaller than every other number in the List. If this does not occure at all you return true, because obviously it was not smaller than any of the others.

Related