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

In C ++, anytime I want to process some elements, 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 also for other collection classes?

+5
source share
6 answers

Right now, I can't think of anything, but using LINQ, you can easily create one IEnumerable<T>that is part of your collection.

As I understand it, the way C # is to see part of the collection as the collection itself and make your methodwork on this sequence. This idea allows the method to be unaware of whether it works on the entire collection or part of it.

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);

and etc.

Compare this with 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++

++ , , . # IEnumerable . - .

+3
// ...
using System.Linq;

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

LINQ, Skip Take.

+4

IEnumerable < > LINQ?

void MyMethod<T>(IEnumerable<T> workSet) {
    foreach (var workItem in workSet) {
        doWorkWithItem(workItem);
    }
}

var dataset = yourArray.SkipWhile(i=>i!=startItem).TakeWhile(i=>i!=endItem);
MyMethod(dataset);

var pagedSet = yourArray.Skip(pageSize * pageNumber).Take(pageSize);
MyMethod(pagedSet);
+1

, LAMBDA ?

public myClass {
    public int Year { get; set; }
    ...
}

...

List<myClass> allClasses = db.GetClasses();
IEnumerable<myClass> subsetClasses = allClasses.where(x => x.Year >= 1990 && x.Year <= 2000);

processSubset(subsetClasses);

skip() take() , , n .

0

, . , . , - :

List<string> lst = new List<string>();
lst = lst.Where(str => str == "Harry" || str == "John" || str == "Joey").ToList();
0

All Articles