In C++, anytime I want to process some range of items I do something like this:
template<class Iterator>
void method(Iterator range_begin, Iterator range_end);
Is there such a convenient way to do this in C#, not only for System.Array
but for other collection classes as well?
// ...
using System.Linq;
IEnumerable<T> GetSubset<T>( IEnumerable<T> collection, int start, int len )
{
// error checking if desired
return collection.Skip( start ).Take( len );
}
I can't think of any at the moment, but using LINQ you can easily create an IEnumerable<T>
representing a part of your collection.
As I understand it, the C# way is to see a part of a collection as a collection itself, and make your method
to work on this sequence. This idea allows the method to be ignorant to whether it's working on the whole collection or its part.
Examples:
void method(IEnumerable<T> collection)
{ ... }
// from 2-nd to 5-th item:
method(original.Skip(1).Take(4));
// all even items:
method(original.Where(x => x % 2 == 0));
// everything till the first 0
method(original.TakeWhile(x => x != 0));
// everything
method(original);
etc.
Compare this to C++:
// from 2-nd to 5-th item:
method(original.begin() + 1, original.begin() + 5);
// everything
method(original.begin(), original.end());
// other two cannot be coded in this style in C++
In C++, your code calculates iterators in order to pass them around, and mark the beginning and the end of your sequence. In C#, you pass lightweight IEnumerable
s around. Due to the lazy evaluation this should have no overhead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With