我需要回傳雙精度陣列中具有奇數索引的元素的總和這是我的代碼:
public static double EvaluateSumOfElementsOddPositions(double[] inputData)
{
var sum = inputData
.Select((v, i) => new { Group = (i % 2 != 0), Value = v })
.GroupBy(x => x.Group)
.Select(g => g.Sum(y => y.Value));
return sum ;
}
但是我有一個錯誤:不能將 IEnumerable 隱式轉換為 double。我不知道我該如何處理……請幫助!
uj5u.com熱心網友回復:
你正在尋找的是這樣的:
public static double EvaluateSumOfElementsOddPositions(double[] inputData)
{
return inputData
.Where((data, index) => index % 2 != 0)
.Sum();
}
如果您不打算在偶數索引處使用元素,則不需要對元素進行分組。
uj5u.com熱心網友回復:
盡管嘗試使用 LINQ 執行此操作是一個不錯的練習,但效率并不高。
GroupBy 將創建一個Dictionary<Tkey, ICollection<TResult>>,或者更準確地說:一個查找表。對于每個元素,它將提取鍵和 TResult。對于 ever 元素,它將檢查鍵是否在查找表中。
- 如果沒有,它會將 TResult 放入一個新的
ICollection<TResult>并將 Key 和集合添加到表中。 - 如果 Key 在表中,它會將 TResult 添加到集合的末尾。
這是相當多的作業,而實際上你唯一想要的是:
public static IEnumerable<double> ToEveryOtherDouble(this IEnumerable<double> doubles)
{
bool everyOther = false;
// will return elements with index 1, 3, 5, ...
// start with true if you want 0, 2, 4, ...
foreach (double d in doubles)
{
if (everyOther)
yield return d;
everyOther = !everyOther;
}
用法:
IEnumerable<double> inputData = ....
double sum = inputData.ToEveryOtherDouble().Sum();
如果您堅持使用 LINQ,請分成兩組:一組包含偶數索引的雙精度數,一組包含奇數索引的雙精度數。
所以組的關鍵: i % 2
double sum = inputData.Select( (d, index) => new
{
Index = index,
Value = d,
})
.GroupBy(x => x.Index % 2, // keySelector: groups with key 0 and key 1
// parameter elementSelector: specify the elements of each group
x => x.Value) // as elements of the group, we only need the double
GroupBy 的結果:兩個組。鍵為 0 的組和鍵為 1 的組。鍵為 0 的組將偶數索引處的雙打作為元素,鍵 1 的組將奇數索引處的雙打作為元素。
繼續 LINQ:如果你只想要偶數索引:
.Where(group => group.Key == 0).Sum();
結論
選擇權在您手中:哪一個更易于閱讀、重用、維護和單元測驗:
double sum = inputData.Select( (d, index) => new
{
Index = index,
Value = d,
})
.GroupBy(x => x.Index % 2, x => x.Value)
.Where(group => group.Key == 0)
.Sum();
或者:
double sum = inputData.ToEveryOtherDouble().Sum();
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/332938.html
