Tutorial :Take a sequence of elements from an array from i to j using C# and extension method



Question:

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


Solution:1

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


Solution:2

var result = myStringArray.Skip(i).Take(j-i);  


Solution:3

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »