I have List
with n items. I wish transform my list to new list, in which no more than n first items.
Example for n=3
:
[1, 2, 3, 4, 5] => [1, 2, 3]
[1, 2] => [1, 2]
What is the shortest way to do this?
I have List
with n items. I wish transform my list to new list, in which no more than n first items.
Example for n=3
:
[1, 2, 3, 4, 5] => [1, 2, 3]
[1, 2] => [1, 2]
What is the shortest way to do this?
If you have C# 3, use the Take
extension method:
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 could 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 it isn't an extension method:
var shortened = SomeClass.Take(list, 3);
You can with Linq
List<int> myList = new List<int>();
myList.Add(1);
myList.Add(2);
myList.Add(3);
myList.Add(4);
myList.Add(5);
myList.Add(6);
List<int> subList = myList.Take<int>(3).ToList<int>();
If you don't have LINQ, try:
public List<int> GetFirstNElements(List<int> list, int n)
{
n = Math.Min(n, list.Count);
return list.GetRange(0, n);
}
otherwise use Take.