How to do Linq aggregates when there might be an empty set?

前端 未结 4 1784
醉酒成梦
醉酒成梦 2020-12-06 01:13

I have a Linq collection of Things, where Thing has an Amount (decimal) property.

I\'m trying to do an aggregate on this for a

4条回答
  •  孤街浪徒
    2020-12-06 01:49

    To get a non-nullable result, you need to cast the amount to a nullable type, and then handle the case of Sum returning null.

    decimal total = myThings.Sum(t => (decimal?)t.Amount) ?? 0;
    

    There's another question devoted to the (ir)rationale.

提交回复
热议问题