Efficiently Generating Collections of Identical Values Using the LINQ Repeat Method in C#

When initializing arrays or lists, you often encounter situations where you need a collection in which the same value is repeated, such as “filling all elements with 0” or “creating a list filled with a specific error message.”

While it is possible to assign values one by one using a for loop, using the Enumerable.Repeat method included in C# LINQ allows you to write initialization logic concisely and declaratively.

In this article, I will explain how to utilize the Repeat method and provide important precautions when handling reference types, using the initialization of a weekly schedule as an example.

目次

Overview of the Enumerable.Repeat Method

Enumerable.Repeat generates a sequence (IEnumerable<T>) where a specified element is repeated a specified number of times.

Syntax:

Enumerable.Repeat(T element, int count)
  • element: The value (or object) you want to repeat.
  • count: The number of times to repeat.

Practical Code Example: Schedule Initialization

The following code is an example of securing schedule slots for one week (7 days) and filling them all with an initial status of “Pending.”

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

namespace ScheduleSystem
{
    class Program
    {
        static void Main()
        {
            // Scenario:
            // When creating a schedule for a new week,
            // we want to initialize the 7 days from Monday to Sunday as "Pending".

            string defaultStatus = "Pending";
            int daysOfWeek = 7;

            // 1. Generate 7 identical strings using Enumerable.Repeat
            // Result: "Pending", "Pending", "Pending", ... (7 items)
            // Call ToArray() at the end to treat it as an array.
            string[] weeklySchedule = Enumerable.Repeat(defaultStatus, daysOfWeek).ToArray();

            // 2. Check the result
            Console.WriteLine("--- Initial Weekly Schedule ---");
            
            // Output with index (using Select overload)
            var displayList = weeklySchedule.Select((status, index) => 
                $"Day {index + 1}: {status}");

            foreach (var item in displayList)
            {
                Console.WriteLine(item);
            }
        }
    }
}

Execution Result:

--- Initial Weekly Schedule ---
Day 1: Pending
Day 2: Pending
Day 3: Pending
Day 4: Pending
Day 5: Pending
Day 6: Pending
Day 7: Pending

Technical Points and Important Precautions

1. Distinction from Range

When handling numbers, it is easy to confuse Repeat with Enumerable.Range, but there is a clear difference.

  • Range: Generates sequential numbers that change, like 1, 2, 3...
  • Repeat: Repeats the same value, like 1, 1, 1...

2. [Most Important] Behavior When Repeating Reference Types

The most important point to watch out for when using Enumerable.Repeat is when repeating “objects (reference types).”

Repeat repeats the “reference to the instance” passed as an argument exactly as is. In other words, all elements will point to the “same instance.”

// [Bad Example]
// Just repeats references to the SAME Person instance 5 times.
var people = Enumerable.Repeat(new Person(), 5).ToList();

// Changing the name of the first element...
people[0].Name = "Tanaka";

// All elements' names change to "Tanaka" (because they look at the same entity).
Console.WriteLine(people[1].Name); // Outputs "Tanaka"

3. When You Want to Generate Individual Instances

If you want to initialize a list with “5 different (independent) Person instances,” it is recommended to combine Range and Select instead of using Repeat.

// [Good Example]
// Since 'new' is called every time inside Select, they become independent instances.
var distinctPeople = Enumerable.Range(0, 5)
                               .Select(_ => new Person())
                               .ToList();

Summary

Enumerable.Repeat is very useful for filling initial values (padding) or generating fixed test data.

  • Use Repeat when handling strings or numbers (value types/immutable types).
  • Use a combination of Range and Select when you want to initialize a list of mutable objects (reference types).

By being conscious of this distinction, you can write robust, bug-free code.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次