3 回答

TA貢獻1824條經驗 獲得超8個贊
如果你想模仿你的程序代碼,你可以使用TakeWhile:
Enumerable.Range(0, int.MaxValue).
Select(i => startValue + (i * increment)).
TakeWhile(i => i <= endValue);
但在我看來,這在性能和可讀性方面更糟糕。

TA貢獻1818條經驗 獲得超8個贊
嘗試Enumerable.Range以模擬for循環:
int startingValue = 1;
int endValue = 13;
int increment = 5;
var result = Enumerable
.Range(0, (endValue - startingValue) / increment + 1)
.Select(i => startingValue + increment * i);
Console.Write(string.Join(", ", result));
結果:
1, 6, 11

TA貢獻1824條經驗 獲得超5個贊
不需要在 LINQ中做任何事情才能像Linq一樣可用,你可以非常接近你的原始版本:
IEnumerable<int> CustomSequence(int startingValue = 1, int endValue = 13, int increment = 5)
{
for (int i = startingValue; i <= endValue; i += increment)
{
yield return i;
}
}
像這樣稱呼
var numbers = CustomSequence();
或對其進行任何進一步的 LINQ:
var firstTenEvenNumbers = CustomSequence().Where(n => n % 2 == 0).Take(1).ToList();
- 3 回答
- 0 關注
- 315 瀏覽
添加回答
舉報