I have a custom type ( Money ) that has an implict conversion to decimal and overloaded operator for + . When I have a list of these types and the linq Sum method is called, the result will be decimal, not Money . How can I give operator + confirmation and return money from Sum ?
Money
+
Sum
internal class Test { void Example() { var list = new[] { new Money(10, "GBP"), new Money(20, "GBP") }; //this line fails to compile as there is not implicit //conversion from decimal to money Money result = list.Sum(x => x); } } public class Money { private Currency _currency; private string _iso3LetterCode; public decimal? Amount { get; set; } public Currency Currency { get { return _currency; } set { _iso3LetterCode = value.Iso3LetterCode; _currency = value; } } public Money(decimal? amount, string iso3LetterCurrencyCode) { Amount = amount; Currency = Currency.FromIso3LetterCode(iso3LetterCurrencyCode); } public static Money operator +(Money c1, Money c2) { if (c1.Currency != c2.Currency) throw new ArgumentException(string.Format("Cannot add mixed currencies {0} differs from {1}", c1.Currency, c2.Currency)); var value = c1.Amount + c2.Amount; return new Money(value, c1.Currency); } public static implicit operator decimal?(Money money) { return money.Amount; } public static implicit operator decimal(Money money) { return money.Amount ?? 0; } }
Sum only knows about number types in System .
System
You can use Aggregate as follows:
Aggregate
Money result = list.Aggregate((x,y) => x + y);
Since this is an Aggregate<Money> call, it will use your Money.operator+ and return a Money object.
Aggregate<Money>
Money.operator+
Source: https://habr.com/ru/post/949719/More articles:Error: "django_comments relationship" does not exist "- djangoStrange flashing on the client of the remote control of the lock when it stops from the client itself - androidHow to convert org-mode table to original tab format? - emacsDetect numbers in html text using jquery - jqueryLinq sum at the facilities? - c #convert sqlalchemy query result to dicts list - pythonCompilation error C: Id returned 1 exit status - cUnrivaled Java Objects - javaWebView with custom HTTP client - javaThe assembly file, called with the command, resets the caller's logging configuration - javaAll Articles