你可以重载Sum来添加自定义类型

Joe*_*ham 11 c# linq ienumerable

我有一个Money结构,有货币和金额.我希望能够使用linq对List进行求和.

public struct Money
{
    public string Currency { get; set; }
    public decimal Amount { get; set; }

    public static Money operator +(Money m1, Money m2)
    {
        if (m1.Currency != m2.Currency)
            throw new InvalidOperationException();

        return new Money() { Amount = m1.Amount + m2.Amount, Currency = m1.Currency };
    }
}
Run Code Online (Sandbox Code Playgroud)

给定上面的代码,如果我有一个具有Money值对象的Items列表,则可以使Sum函数与Money值对象一起使用.

Items.Sum(m => m.MoneyValue);
Run Code Online (Sandbox Code Playgroud)

Jes*_*det 26

public static class SumExtensions
{
    public static Money Sum(this IEnumerable<Money> source)
    {
        return source.Aggregate((x, y) => x + y);
    }

    public static Money Sum<T>(this IEnumerable<T> source, Func<T, Money> selector)
    {
        return source.Select(selector).Aggregate((x, y) => x + y);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

IEnumerable<Money> moneys = ...
Money sum = moneys.Sum();
Run Code Online (Sandbox Code Playgroud)

IEnumerable<Transaction> txs = ...
Money sum = txs.Sum(x=>x.Amount);
Run Code Online (Sandbox Code Playgroud)