HomeSearch

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.Int, uintStrings
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.