What's the neatest way to achieve “MinOrDefault” in Linq?

前端 未结 5 1310
粉色の甜心
粉色の甜心 2020-12-08 05:47

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

5条回答
  •  不知归路
    2020-12-08 06:38

    This approach will return the single smallest Amount value from itemList. In theory this should avoid multiple round trips to the database.

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

    The null reference exception is no longer caused because we are using a nullable type.

    By avoiding the use of executing methods such as Any before calling Min, we should only be making one trip to the database

提交回复
热议问题