❔ Iterate over a range
What's the equivalent of this (rust)
in C#? So basically, how to loop over a range?
I'm not a big fan of C-style loops 😄 I find them very noisy and cumbersome.
14 Replies
Oh thanks! I'm really starting out so I didn't know about extension but that does make sense.
It's not a big deal, but I highly doubt I'd ever need ranges from the end of int. Is there any way I could specialize this so it doesn't do the branching stuff to account for
IsFromEnd
?
that would still require branching though
(i.e. some form of conditional to check IsFromEnd
)
I thought there might be a specialized type for ranges whose bounds are only from the start (not IsFromEnd
) but I might just be wishful 🙂You could use
Enumerable.Range()
too
A bit less ergonomic, but yeah that works 🙂
thanks to both of you
will make it a little more ergonomic
hmmm yeah that could be a good solution
Obviously I'm pretty new to C# so, is this concept of iterating over a range common/accepted in this language?
I feel like the fact that this isn't built-in might mean that I'm going against the grain here
Well, ranges are quite a new thing (by ranges I mean the
x..y
syntax) and they don't really represent a "from-to" in a numeric sense. After all, what does ^7..
, or "from seventh from the end, to the end" mean in terms of numbers?
int.MaxValue - 7
to int.MaxValue
?
inf - 7
to inf
?
You usually see regular for
loops if you really need the index
Most commonly, though, you just... don't need the indexyeah sure, I imagine with most collections I'd just use foreach and it'd work out-of-the-box, but for algorithms it's not rare to need either the index, or a (index, item) pair
Can't say I see much that would require an index
Besides maybe some sort of a parser where you might have to look up
i + 2
item ahead or somethingwell, just as an example, sorting algorithms are usually expressed using indexes
doesn't really matter though, I do agree that it's not a common thing
.Sort()
yeah yeah, I'm just messing around to get a feel for the language :p In any case, there's more than one way to sort a collection depending on the performance characteristics that you seek. But I digress, performance is not a concern here, ultimately I was just curious.
So, yeah, to sum it up: most commonly you use a foreach or LINQ, on the rare cases you need an index you use a classic
for
loopalright, thanks 🙂
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.