TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Take, TakeWhile: Extension Methods

These C# example programs use the Take and TakeWhile extension methods. They require System.Linq.

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.

Extension Method

Example. Here we 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. It receives an element count.

Here: We look at a couple simple examples of how Take works. Then we look at using Reverse with Take.

Reverse

C# program that uses Take

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

In this example, the first Take call returns the first two elements in the List. This could display the two oldest, first elements. The second Take call above is chained after a Reverse<string> call. It operates on the result of Reverse.

Note: This part will print out the last two elements in Reverse order. This could be used to display the newest elements.

And: The final Take call above uses the top 1000 elements, which is nonsense as there are not 1000 elements in the List.

List

However: The final Take call shows that Take will manage bad parameters without a problem.

TakeWhile returns elements while a Predicate matches. The Predicate returns true or false. When it returns false, TakeWhile returns. TakeWhile operates from the beginning of an IEnumerable collection.

Predicate

Next: In this program, an integer array of five elements is declared. The first three numbers in it are odd, while the last two are even.

Odd, Even

And: The TakeWhile extension method is invoked. It returns the first three odd numbers, but not the even numbers at the end.

C# program that uses TakeWhile method

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// Contains five numbers.
	int[] values = { 1, 3, 5, 8, 10 };

	// Take all non-even (odd) numbers.
	var result = values.TakeWhile(item => item % 2 != 0);

	// Display result.
	foreach (int value in result)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

1
3
5

Reading the lambda expression. How can you read the lambda expression? The name 'item' is just a temporary variable name. Each element becomes an item, and then the function returns true only if the value is not evenly divisible by two.

LambdasModulo

Discussion. Skip is useful when paired with Take. It 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.

Skip, SkipWhile

Summary. 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. It is helpful in higher-level programs.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf