2015-02-24 51 views
1

通過傳遞resultSelector函數或直接將Aggregate結果值傳遞給函數來使用LINQ Aggregate方法時,是否有實際區別?LINQ.Aggregate與結果選擇器參數的區別或直接調用方法

代碼示例(有更好的方式來做到這一點,但是這說明了什麼問題相當不錯):

var list = new string[] { "a", "b", "c" }; 
list.Aggregate(new StringBuilder(), (sb, s) => sb.AppendLine(s), sb => sb.ToString()); 
list.Aggregate(new StringBuilder(), (sb, s) => sb.AppendLine(s)).ToString(); 

最終,這兩個語句返回相同的字符串。 是否有可以單向編寫的代碼,但不是另一種?

回答

5

據我所知,沒有區別。看着我的Edulinq實現,我只是通過調用超載選擇實現,而不會選擇過載,然後與身份轉變:

public static TAccumulate Aggregate<TSource, TAccumulate>(
    this IEnumerable<TSource> source, 
    TAccumulate seed, 
    Func<TAccumulate, TSource, TAccumulate> func) 
{ 
    return source.Aggregate(seed, func, x => x); 
} 

這本來是完全合理的做到這一點的其他方式,例如

public static TResult Aggregate<TSource, TAccumulate, TResult>(
    this IEnumerable<TSource> source, 
    TAccumulate seed, 
    Func<TAccumulate, TSource, TAccumulate> func, 
    Func<TAccumulate, TResult> resultSelector) 
{ 
    var intermediate = source.Aggregate(seed, func); 
    return resultSelector(intermediate); 
} 

現在只是因爲它們相當並不意味着過載是無用的。例如,有時也可能是更容易使用lambda表達式來表示結果選擇:

var result = list.Aggregate(..., ..., total => total < 0 ? total + 1 
                 : total - 1); 

您可以創建一個單獨的方法(或只是一個Func<TArg, TResult>)要做到這一點,但在某些情況下,你想要做的整個事情在一個單一的方法調用。

簡而言之 - 在每個個案中使用哪種方法最適合您;就我所知,它們是相等的。