Get the first few items from a list in C #

I have Listwith n elements. I want to convert my list to a new list with no more than n first elements.

Example for n=3:

[1, 2, 3, 4, 5] => [1, 2, 3]
[1, 2] => [1, 2]

What is the shortest way to do this?

+3
source share
5 answers

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);
+13
source

If you do not 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.

+7
source

Take

myList.Take(3);
+6

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>();
+1
var newList = List.Take(3);
+1

Source: https://habr.com/ru/post/1736163/


All Articles