這聽起來像你想提取字符串屬性和雙重屬性的一種方式(假設「十進制」在您的文章是一個錯字,而不是在你的代碼「雙」) - Func
是合適的位置:
public static double SumIf<T>(this IEnumerable<T> source,
string targetText,
Func<T, string> textSelector,
Func<T, double> valueSelector)
{
double sum = 0;
foreach (T item in source)
{
if (textSelector(item) == targetText)
{
sum += valueSelector(item);
}
}
return sum;
}
(請注意,我已經刪除未使用的初始參數,並使其列表本身上的擴展方法不使用。價值感覺像ab它一聞到我的......我也改變了參數類型IEnumerable<T>
因爲你不需要它是一個真正的列表)
注意,這實際上大多等同於:
public static double SumIf<T>(this IEnumerable<T> source,
string targetText,
Func<T, string> textSelector,
Func<T, double> valueSelector)
{
return source.Where(x => textSelector(x) == targetText)
.Sum(valueSelector);
}
我個人可能去一個一般謂詞函數而不是字符串和文本選擇:
public static double SumIf<T>(this IEnumerable<T> source,
Func<T, bool> predicate,
Func<T, double> valueSelector)
{
return source.Where(predicate)
.Sum(valueSelector);
}
然後你會跟
double sum = list.SumIf(x => x.Name == "mort", x => x.Amount);
叫它
...這似乎只是作爲對我好爲:
double sum = list.SumIf("mort", x => x.Name, x => x.Amount);
...但明顯更靈活。
正如評論中指出的,你真的需要這個嗎?您是否在足夠的地方使用它以使簡單的Where/Sum調用無法忍受?
double sum = list.Sum(x => x.Name == "mort" ? x => x.Amount : 0d);
沒有上面的方法給你什麼問題? – 2012-03-17 23:01:01
['Aggregate'](http://msdn.microsoft.com/library/system.linq.enumerable.aggregate.aspx)不適合你嗎?或['Where'](http://msdn.microsoft.com/library/system.linq.enumerable.where.aspx)後跟['Sum'](http://msdn.microsoft.com/library/system .linq.enumerable.sum.aspx)?或者你想要一個助手擴展方法? – BACON 2012-03-17 23:02:36