Dre*_*kes 7 c# linq sequences enumerable infinite-sequence
给出一个起始数字,想象一下它连续一半的无限序列.
1, 0.5, 0.25, 0.125, ...
Run Code Online (Sandbox Code Playgroud)
(忽略其中固有的任何数值不稳定性double.)
这可以在单个表达式中完成而无需编写任何自定义扩展方法或生成器方法吗?
n8w*_*wrl 11
我不知道单表达方式,但我在这里找到了这个聪明的生成器代码:http://csharpindepth.com/articles/Chapter11/StreamingAndIterators.aspx
public static IEnumerable<TSource> Generate<TSource>(TSource start,
Func<TSource,TSource> step)
{
TSource current = start;
while (true)
{
yield return current;
current = step(current);
}
}
Run Code Online (Sandbox Code Playgroud)
在你的情况下,你会使用它:
foreach (double d in Generate<double>(1, c => c / 2))
{
...
}
Run Code Online (Sandbox Code Playgroud)
小智 10
为了好玩,这里有一个在单个表达式中创建真实无限序列的技巧.前两个定义是类字段,因此它们不需要初始化表达式.
double? helper;
IEnumerable<double> infinite;
infinite = new object[] { null }.SelectMany(dummy => new double[] { (helper = (helper / 2) ?? 1).Value }.Concat(infinite));
Run Code Online (Sandbox Code Playgroud)