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

// ...
using System.Linq;

IEnumerable<T> GetSubset<T>( IEnumerable<T> collection, int start, int len )
{
    // error checking if desired
    return collection.Skip( start ).Take( len );
}

If you use LINQ, take a look at Skip and Take.


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.

Tags:

C#

.Net