If you have C # 3, use the extension method Take:
var list = new [] {1, 2, 3, 4, 5};
var shortened = list.Take(3);
See: http://msdn.microsoft.com/en-us/library/bb503062.aspx
If you have C # 2, you can write the equivalent:
static IEnumerable<T> Take<T>(IEnumerable<T> source, int limit)
{
foreach (T item in source)
{
if (limit-- <= 0)
yield break;
yield return item;
}
}
The only difference is that this is not an extension method:
var shortened = SomeClass.Take(list, 3);
source
share