using System;
using System.Linq;
public class RangeArrayInitializer
{
public static void Main()
{
int start = 1;
int end = 10;
// 1. Standard LINQ Enumerable.Range approach
int[] linqArray = CreateRangeArrayWithLinq(start, end);
Console.WriteLine($"LINQ Array [1, 10]: {string.Join(", ", linqArray)}");
// 2. High-performance Span<T> population approach
int[] spanArray = CreateRangeArrayWithSpan(start, end);
Console.WriteLine($"Span Array [1, 10]: {string.Join(", ", spanArray)}");
// 3.Custom step increment approach
int[] stepArray = CreateRangeArrayWithStep(1, 10, 2);
Console.WriteLine($"Step Array [1, 10] step 2: {string.Join(", ", stepArray)}");
}
/// <summary>
/// Generates an integer array using LINQ Enumerable.Range.
/// Provides clear declarative intent for general-purpose applications.
/// </summary>
/// <param name="start">Starting integer of the range</param>
/// <param name="endInclusive">Ending integer of the range (inclusive)</param>
/// <returns>An array containing sequential values</returns>
public static int[] CreateRangeArrayWithLinq(int start, int endInclusive)
{
// Calculate total element count based on inclusive boundaries
int count = (endInclusive - start) + 1;
// Enumerable.Range generates sequence, ToArray materializes directly into int[]
return Enumerable.Range(start, count).ToArray();
}
/// <summary>
/// Generates an array using Span<T> for high memory efficiency and modern indexing.
/// </summary>
/// <param name="start">Starting integer of the range</param>
/// <param name="endInclusive">Ending integer of the range (inclusive)</param>
/// <returns>An array filled sequentially via Span view</returns>
public static int[] CreateRangeArrayWithSpan(int start, int endInclusive)
{
int count = (endInclusive - start) + 1;
int[] result = new int[count];
// Wrap array in Span for fast stack-friendly element assignment
Span<int> span = result;
for (int i = 0; i < span.Length; i++) {
span[i] = start + i;
}
return result;
}
/// <summary>
/// Generates an array supporting non-unit step sizes 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>An array with values offset by step size</returns>
public static int[] CreateRangeArrayWithStep(int start, int endInclusive, int step)
{
int count = ((endInclusive - start) / step) + 1;
// Projects index multiplication to compute dynamic step intervals
return Enumerable.Range(0, count)
.Select(i => start + (i * step))
.ToArray();
}
}
/*
run:
LINQ Array [1, 10]: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Span Array [1, 10]: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Step Array [1, 10] step 2: 1, 3, 5, 7, 9
*/