Here we see a generic method, which lets it act on any type. Our Slice method here uses this ability to simulate the built-in slice functionality of Python and other languages.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int[] a = new int[]
{
1,
2,
3,
4,
5,
6,
7
};
foreach (int i in a.Slice(0, 1))
{
Console.WriteLine(i);
}
Console.WriteLine();
foreach (int i in a.Slice(0, 2))
{
Console.WriteLine(i);
}
Console.WriteLine();
foreach (int i in a.Slice(2, 5))
{
Console.WriteLine(i);
}
Console.WriteLine();
foreach (int i in a.Slice(2, -3))
{
Console.WriteLine(i);
}
}
}
public static class Extensions
{
/// <summary>
/// Get the array slice between the two indexes.
/// ... Inclusive for start index, exclusive for end index.
/// </summary>
public static T[] Slice<T>(this T[] source, int start, int end)
{
// Handles negative ends.
if (end < 0)
{
end = source.Length + end;
}
int len = end - start;
// Return new array.
T[] res = new T[len];
for (int i = 0; i < len; i++)
{
res[i] = source[i + start];
}
return res;
}
}
1
1
2
3
4
5
3
4