C# Take

LINQ (language integrated query)

Take returns the first specified number of elements. It acts upon an IEnumerable sequence. It returns another IEnumerable sequence containing the specified elements. We see basic usages of this extension method. We see how to Take in reverse order.

Example

Note

Here we see how you can use the Take extension method in the C# language. Take is a method in the System.Linq namespace that allows you to get the first several elements from a sequence. We look at a couple simple examples of how Take works. Then we look at using Reverse with Take.

This C# example program uses the Take extension method. It requires System.Linq.

Program that uses Take [C#]

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
	List<string> list = new List<string>();
	list.Add("cat");
	list.Add("dog");
	list.Add("programmer");

	// Get first 2 elements
	var first = list.Take(2);
	foreach (string s in first)
	{
	    Console.WriteLine(s);
	}
	Console.WriteLine();

	// Get last 2 elements reversed
	var last = list.Reverse<string>().Take(2);
	foreach (string s in last)
	{
	    Console.WriteLine(s);
	}
	Console.WriteLine();

	// Get first 1000 elements
	var all = list.Take(1000);
	foreach (string s in all)
	{
	    Console.WriteLine(s);
	}
	Console.WriteLine();
    }
}

Output

cat
dog

programmer
dog

cat
dog
programmer
List type.

Description. The first Take method call above returns the very first two elements in the List, which could be used to display the two oldest, first elements. The second Take call above is chained after a Reverse<string> call. This means it operates on the result of Reverse. This part will print out the last two elements in Reverse order. This could be used to display the newest elements.

Next steps. The final Take call above uses the top 1000 elements, which is nonsense as there are not 1000 elements in the List. However, it shows that Take will manage bad parameters without a problem.

Skip

Programming tip

Here we mention that the Skip extension that is also from the System.Linq namespace is very useful when paired with the Take extension method. The Skip method allows you to avoid the first several elements in the sequence. When you combine Skip with Take, you can indicate elements that you want to avoid based on a numeric pattern. There is more information on the Skip extension method available.

Skip Extension Method

Summary

The C# programming language

We saw examples of using the Take method in the C# language. Also, we saw Reverse with Take, and how to use simple extension methods. Take method performance is fairly good, but it is not as fast as custom extension methods may be. Therefore, Take is not suitable for performance-critical applications.

LINQ Examples
.NET