Jay*_*uzi 15 c# linq optimization sequences
我正在尝试用巧妙,清晰和简单的方法来编写描述给定范围内整数序列的代码.
这是一个例子:
IEnumerable<int> EnumerateIntegerRange(int from, int to)
{
for (int i = from; i <= to; i++)
{
yield return i;
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 63
这已经在框架中:Enumerable.Range.
对于其他类型,您可能对我的MiscUtil库中的范围类感兴趣.
或者,扩展方法的流畅界面:
public static IEnumerable<int> To(this int start, int end)
{
return start.To(end, i => i + 1);
}
public static IEnumerable<int> To(this int start, int end, Func<int, int> next)
{
int current = start;
while (current < end)
{
yield return current;
current = next(current);
}
}
Run Code Online (Sandbox Code Playgroud)
用过:
1.To(100)
Run Code Online (Sandbox Code Playgroud)