TheDeveloperBlog.com

Home | Contact Us

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

C# Enumerable.Repeat Example

This C# example program uses the Repeat method on the Enumerable type. It requires System.Linq.

Enumerable.Repeat returns a collection with repeated elements.

In the first argument, we specify a value—this is repeated the number of times specified in the second argument. This method is located in the System.Linq namespace.

Example. The Enumerable.Repeat method receives two arguments: the value you want to be repeated, and the number of times you want it to be repeated. This means that Enumerable.Repeat(1, 10) will yield ten ones in a sequence.

Note: The result of Enumerable.Repeat is an IEnumerable of the type specified, such as an IEnumerable<int>.

C# program that uses Enumerable.Repeat

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// Create sequence of ten ones.
	var integers = Enumerable.Repeat(1, 10);
	// Display.
	foreach (int value in integers)
	    Console.WriteLine(value);
    }
}

Output

1
1
1
1
1
1
1
1
1
1

Converting to array. You can convert the IEnumerable result from Enumerable.Repeat to an array or List. Please use the ToArray or ToList methods and assign the result to a new array or List variable.

ToArrayToList

Summary. By providing a declarative way to create an array of repeated elements, the Enumerable.Repeat method can help simplify certain programs in the C# language. It can be used with many types, including ints and strings.

IntStrings


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