Enumerable.Range-什么时候使用有意义? [英] Enumerable.Range - When does it make sense to use?
问题描述
编程时,几乎是本能地决定何时使用for循环或foreach,但是选择使用Enumerable.Range的决定因素或问题空间是什么?
When programming it's almost instinctive deciding when to use a for loop, or foreach, but what is the determining factors or problem space for choosing to use Enumerable.Range?
当我们要迭代一定次数(通过简单数据类型)以计算/执行重复任务时,选择 For循环.
A For Loop is chosen when we want to iterate a set number of times (over a simple data type) to calculate/do a repetitive task.
对于每个人是相似的,但是当我们要遍历一系列复杂对象以计算/执行重复任务时选择.
A For Each is similar, but chosen when we want to iterate over a list of complex objects to calculate/do a repetitive task.
再次,使用Enumerable.Range的决定因素是什么?
Again, what's the determining factors for using an Enumerable.Range?
IEnumerable<int> squares = Enumerable.Range(4, 3).Select(x => x * x);
推荐答案
foreach
是关于在现有集合/集合上进行迭代.
Enumerable.Range
用于生成一个集合/集合.通常,您不想为Enumerable.Range
-您只需要编写更长的样板代码,并要求您分配某种存储方式(例如
Enumerable.Range
is for generating a set/collection. You wouldn't, generally, want to write a for
loop just to generate a set if it can be generated by Enumerable.Range
- you'd just be writing boilerplate code that's longer and requires you to allocate some kind of storage (e.g. a List<int>
) to populate first.
这篇关于Enumerable.Range-什么时候使用有意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!