I have a list of type IList<Effort>
. The model Effort contains a float
called Amount
. I would like to return the sum of Amount
for the whole list, in F#. How would this be achieved?
views:
120answers:
4Seq.fold (fun acc (effort: Effort) -> acc + effort.Amount) 0.0 efforts
One detail that may be interesting is that you can also avoid using type annotations. In the code by sepp2k, you need to specify that the effort
value has a type Effort
, because the compiler is processing code from the left to the right (and it would fail on the call effort.Amount
if it didn't know the type). You can write this using pipelining operator:
efforts |> Seq.fold (fun acc effort -> acc + effort.Amount) 0.0
Now, the compiler knows the type of effort
because it knows that it is processing a collection efforts
of type IList<Effort>
. It's a minor improvement, but I think it's quite nice.
Upvoted the answers of Seq.fold
, pipelined Seq.fold
, and pipelined Seq.sumBy
(I like the third one best).
That said, no one has mentioned that seq<'T>
is F#'s name for IEnumerable<T>
, and so the Seq
module functions work on any IEnumerable
, including IList
s.