Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to initialize a list with a range of numbers in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Linq;

public class RangeListInitializer
{
    public static void Main()
    {
        int start = 1;
        int end = 10;

        // 1. Standard LINQ Enumerable.Range approach
        List<int> linqList = CreateRangeListWithLinq(start, end);
        Console.WriteLine($"LINQ List [1, 10]: {string.Join(", ", linqList)}");

        // 2. High-performance imperative approach with pre-allocated capacity
        List<int> loopList = CreateRangeListWithLoop(start, end);
        Console.WriteLine($"Loop List [1, 10]: {string.Join(", ", loopList)}");

        // 3. Flexible method supporting non-unit step increments
        List<int> stepList = CreateRangeListWithStep(1, 10, 2);
        Console.WriteLine($"Step List [1, 10] step 2: {string.Join(", ", stepList)}");
    }

    /// <summary>
    /// Generates a List<int> containing a sequential range [start, endInclusive].
    /// Uses Enumerable.Range to express intent cleanly in a functional style.
    /// </summary>
    /// <param name="start">Starting integer of the range</param>
    /// <param name="endInclusive">Ending integer of the range (inclusive)</param>
    /// <returns>A List filled with sequential values</returns>
    public static List<int> CreateRangeListWithLinq(int start, int endInclusive)
    {
        // Enumerable.Range takes starting value and total count
        int count = (endInclusive - start) + 1;

        // ToList materializes the sequence into a mutable List<int>
        return Enumerable.Range(start, count).ToList();
    }

    /// <summary>
    /// Generates a List<int> using pre-allocated capacity and a loop.
    /// Eliminates memory re-allocations during population for optimal speed.
    /// </summary>
    /// <param name="start">Starting integer of the range</param>
    /// <param name="endInclusive">Ending integer of the range (inclusive)</param>
    /// <returns>A pre-sized List populated sequentially</returns>
    public static List<int> CreateRangeListWithLoop(int start, int endInclusive)
    {
        int count = (endInclusive - start) + 1;

        // Pre-allocate List capacity to avoid internal array resize overhead
        List<int> result = new List<int>(count);

        for (int current = start; current <= endInclusive; current++) {
            result.Add(current);
        }

        return result;
    }

    /// <summary>
    /// Creates a List<int> supporting custom step intervals using LINQ projection.
    /// </summary>
    /// <param name="start">Starting integer</param>
    /// <param name="endInclusive">Maximum threshold bound</param>
    /// <param name="step">Increment between sequential numbers</param>
    /// <returns>A List of numbers incremented by the specified step</returns>
    public static List<int> CreateRangeListWithStep(int start, int endInclusive, int step)
    {
        int count = ((endInclusive - start) / step) + 1;

        // Select calculates custom step intervals based on element index
        return Enumerable.Range(0, count)
                         .Select(i => start + (i * step))
                         .ToList();
    }
}


/*
run:

LINQ List [1, 10]: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Loop List [1, 10]: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Step List [1, 10] step 2: 1, 3, 5, 7, 9

*/

 



answered Aug 17 by avibootz
...