Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a subset of a collection to a C# method?

Tags:

c#

.net

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?

like image 563
andriej Avatar asked Aug 11 '11 18:08

andriej


2 Answers

// ...
using System.Linq;

IEnumerable<T> GetSubset<T>( IEnumerable<T> collection, int start, int len )
{
    // error checking if desired
    return collection.Skip( start ).Take( len );
}
like image 106
Ed S. Avatar answered Oct 13 '22 02:10

Ed S.


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 IEnumerables around. Due to the lazy evaluation this should have no overhead.

like image 23
Vlad Avatar answered Oct 13 '22 00:10

Vlad