2016-02-24 57 views
5

對於c#Enumerable.Sum<TSource> Method (IEnumerable<TSource>, Func<TSource, Int64>)不支持ulong類型作爲Mehtonf的返回類型,除非我將ulong轉換爲longc#Enumerable.Sum方法不支持ulong類型

public class A 
{ 
    public ulong id {get;set;} 

} 




publec Class B 
{ 
    public void SomeMethod(IList<A> listOfA) 
    { 
     ulong result = listofA.Sum(A => A.Id); 
    } 
} 

的compliler會拋出兩個錯誤:

  1. enter image description here
  2. enter image description here

    除非我做

ulong result = (ulong)listOfA.Sum(A => (long)A.Id)

無論如何解決這個問題沒有鑄造?謝謝!

回答

9

您可以改用Aggregate

ulong result = listOfULongs.Aggregate((a,c) => a + c); 

或者在特定情況下

ulong result = listOfA.Aggregate(0UL, (a,c) => a + c.Id); 

你也應該考慮,如果你真的應該首先使用一個無符號值類型。

+0

謝謝,這似乎是解決問題的一個很好的方式。我使用'ulong'的原因是因爲Id不能爲負數。你認爲我真的應該使用'長'而不是? –

+1

@ Z.Z。 - 如果你沒有處理負數,並且你的總和超過了9,223,372,036,854,775,807',但是不超過'18,446,744,073,709,551,615',那麼'ulong'是個好主意。否則'長'是一個完美的選擇。 – Enigmativity

4

因爲它不是作爲BCL的一部分提供,您可以編寫自己的擴展方法來爲ulong提供過載:

public static ulong Sum<TSource>(
    this IEnumerable<TSource> source, Func<TSource, ulong> summer) 
{ 
    ulong total = 0; 

    foreach(var item in source) 
     total += summer(item); 

    return total; 
} 
+0

不錯的答案,但是這會給編譯器錯誤「CS0165使用未分配的局部變量總數」。你需要明確指定'total'。 – Enigmativity

+0

謝謝你,我正在編寫代碼,並沒有通過編譯器運行它,我會更新它。 –

+0

感謝您的回答!擴展方法似乎是一個不錯的解決方案! –