Search code examples
c#linqmin

How to achieve "MinOrDefault" in LINQ?


I'm producing a list of decimal values from a LINQ expression and I want the minimum non zero value. However it's entirely possible that the LINQ expression will result in an empty list.

This will raise an exception and there is no MinOrDefault to cope with this situation.

decimal result = (from Item itm in itemList
                  where itm.Amount > 0
                  select itm.Amount).Min();

How can I set the result to 0 if the list is empty?


Solution

  • decimal? result = (from Item itm in itemList
                      where itm.Amount != 0
                      select (decimal?)itm.Amount).Min();
    

    Note the conversion to decimal?. You'll get an empty result if there are none (just handle that after the fact - I'm mainly illustrating how to stop the exception). I also made "non-zero" use != rather than >.