tags:

views:

108

answers:

5

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?

+12  A: 

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);
Daniel Earwicker
+5  A: 

You can use Take

myList.Take(3);
Chad
+1  A: 

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>();
David Basarab
A lot of the generics can be inferred, in my opinion.
Dave Van den Eynde
This could be simplified to myList.Take(3).ToList() per @Dave's comment.
jrummell
+6  A: 

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.

Simon
+1  A: 
var newList = List.Take(3);
Kevin
The length checking is not required.
Dave Van den Eynde