2012-12-01 12 views
11

Posiadam niestandardowy typ (Money), który ma domyślną konwersję na dziesiętny i przeciążony operator dla +. Kiedy mam listę tych typów i wywołuję metodę linq Sum, wynik jest dziesiętny, a nie Money. Jak mogę przekazać dyspozycyjność operatora + i zwrócić pieniądze z Sum?Przeciążenie operatora i suma Linq w języku C#

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; 
    } 
} 

Odpowiedz

12

Sum tylko wie o rodzajach numer w System.

Można użyć Aggregate takiego:

Money result = list.Aggregate((x,y) => x + y); 

Ponieważ dzwoni Aggregate<Money> będzie używać Money.operator+ i zwracają Money obiekt.

+3

skończyło się dodanie moje własne 'Sum' publicznych klasy statyczne MoneyHelpers {public static Pieniądze Sum IEnumerable (to źródło, Func wyboru) {var pieniądze = source.Select (wybór); return monies.Aggregate ((x, y) => x + y); } } – ilivewithian

+0

Świetna rada. Dzięki. – Joe

Powiązane problemy