views:

65

answers:

3

I have an Array<string>. I have to take all elements from i to j. How can I make this using an extension method?

+9  A: 

Try the following.

public static IEnumerable<T> GetRange<T>(this IEnumerable<T> enumerable, int start, int end) {
  return enumerable.Skip(start).Take(end-start); 
}

Then you can do

Array<string> arr = GetSomeArray();
var res = arr.GetRange(i,j);
JaredPar
+1  A: 
var result = myStringArray.Skip(i).Take(j-i);
BFree
+2  A: 

You could just use ArraySegment<T>.

If you need this returned as an IEnumerable<T>, the options using Skip/Take already listed will work very well.

Reed Copsey