2012-12-01 31 views
11

Tôi có loại tùy chỉnh (Money) có chuyển đổi ngụ ý thành số thập phân và toán tử quá tải cho +. Khi tôi có danh sách các loại này và gọi phương thức linq Sum kết quả là số thập phân, không phải là Money. Làm thế nào tôi có thể cung cấp cho các quy tắc điều hành + và trả lại tiền từ Sum?Quá tải của nhà khai thác và LINQ Sum trong 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; 
    } 
} 

Trả lời

12

Sum chỉ biết về các loại số trong System.

Bạn có thể sử dụng Aggregate như thế này:

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

Bởi vì đây đang kêu gọi Aggregate<Money>, nó sẽ sử dụng Money.operator+ của bạn và trả về một đối tượng Money.

+3

tôi đã kết thúc thêm riêng 'Sum' MoneyHelpers public class tĩnh của tôi { public static tiền Sum (IEnumerable nguồn này, Func selector) {var tiền = source.Select (selector); monies trả về .ggregate ((x, y) => x + y); } } – ilivewithian

+0

Mẹo hay. Cảm ơn. – Joe

Các vấn đề liên quan