在F#中,只需说出[1..100]就可以生成一组数字.
我想在C#中做类似的事情.这是我到目前为止所提出的:
public static int[] To(this int start, int end)
{
var result = new List<int>();
for(int i = start; i <= end; i++)
result.Add(i);
return result.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
通过这样做,我现在可以通过说1.To(100)创建一个集合
不幸的是,这并不像[1..100]那样可读.有没有人想出更好的方法在C#中做到这一点?如果它是小写的,它是否更具可读性?1.to(100),例如?或者,"To"是一个坏词?类似于1.Through(100)更具可读性吗?
只是寻找一些想法.有没有其他人想出更优雅的解决方案?
编辑: 阅读完回复后,我使用以下范围重新编写了我的To方法:
public static int[] To(this int start, int end)
{
return Enumerable.Range(start, end - start + 1).ToArray();
}
Run Code Online (Sandbox Code Playgroud)
我仍在寻找关于1.To(100)的可读性的想法
我喜欢使用的想法To
.替代方案Enumerable.Range
有一个微妙的缺陷imo.第二个参数不是最后一个元素的值,它是枚举的长度.这就是我过去所做的:
public IEnumerable<int> To(this int start, int stop)
{
while (start <= stop)
yield return start++;
}
Run Code Online (Sandbox Code Playgroud)
编辑:如果您想将结果作为int[]
,只需添加.ToArray()
:
int[] theSet = 1.To(100).ToArray();
Run Code Online (Sandbox Code Playgroud)