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

前端 未结 5 1309
粉色の甜心
粉色の甜心 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条回答
  •  猫巷女王i
    2020-12-08 06:27

    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 >.

提交回复
热议问题