How to handle nulls in LINQ when using Min or Max?

后端 未结 5 1410
暖寄归人
暖寄归人 2020-12-14 05:48

I have the following Linq query:

result.Partials.Where(o => o.IsPositive).Min(o => o.Result)

I get an exception when result.Parti

5条回答
  •  长情又很酷
    2020-12-14 06:39

    You can't use Min (or Max) if the sequence is empty. If that shouldn't be happening, you have a different issue with how you define result. Otherwise, you should check if the sequence is empty and handle appropriately, eg:

    var query = result.Partials.Where(o => o.IsPositve);
    min = query.Any() ? query.Min(o => o.Result) : 0; // insert a different "default" value of your choice...    
    

提交回复
热议问题