The sum of the specific property of all items in the list.

Take the following example:

I have a class

public class SomeItem
{
    public string Name;
    public DateTime Published;
    public uint16 Size;
}

I have List<SomeItem>one and I want to calculate the total size of all the elements.
In C # I will just write

var totalSize = items.Sum((i) => i.Size);

I looked at the List functions in F #, but they always complain about types.

How do you write this in F #?

(I tried search engines, but search engine support for F # is terrible)

+3
source share
3 answers

Assuming you have a type value IEnumerable<Item>, you can use sum_byfrom a module Seq:

let totalSize = items |> Seq.sum_by (fun (i : Item) -> i.Size)

, F # Microsoft.FSharp.Collections.List<T> , , System.Collections.Generic.List<T>, . Seq IEnumerable<T>, IEnumerable<T> F # #.

+8
let totalSize = items |> List.sum_by (fun i -> i.Size)

LINQ F # , , , , , ( , IEnumerable<T>).

+2

This is a crease in F # and other functional languages. Find examples of Seq.fold.

+1
source

Source: https://habr.com/ru/post/1707684/


All Articles