How to create a sequence of integers in C?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Creating integer sequences in C# is a common task in iteration, test data generation, and range-based processing. You can build sequences with loops, Enumerable.Range, iterators, or custom step logic. The best choice depends on readability, performance expectations, and whether you need lazy evaluation.
Enumerable.Range for Standard Sequences
For contiguous ascending ranges, Enumerable.Range is usually the cleanest option.
This creates values from 1 to 10 lazily. It is concise and idiomatic.
Traditional Loop for Full Control
A for loop is best when you need custom bounds, side effects, or mutable accumulation.
This style is explicit and easy to debug.
Generate Sequences With Custom Step
Enumerable.Range does not support arbitrary step sizes directly. Combine it with projection:
This works for arithmetic progressions and remains lazy until enumerated.
Descending Sequences
For descending order, use reverse projection or loop.
You can also generate ascending first and call Reverse, but direct expression is often clearer.
Iterator Method for Reusable Ranges
When sequence rules are reused in multiple places, create an iterator method with yield return.
This gives flexibility for both ascending and descending generation.
Materialized Versus Lazy Sequences
LINQ sequences are lazy by default. If you need repeated indexed access, materialize once.
Lazy evaluation is memory-efficient for single-pass processing. Materialization is better when iterating many times.
Performance Notes
Enumerable.Range is optimized and generally fast for simple integer ranges. For very hot loops in performance-critical code, direct loops may still be preferable due to reduced iterator overhead and allocation behavior in surrounding operations.
Benchmark before optimizing. In many business applications, readability gains from LINQ outweigh micro-optimizations.
Common Pitfalls
- Confusing
countwith end value inEnumerable.Range. - Using
steplogic with potential zero step and no validation. - Materializing large ranges unnecessarily with
ToListorToArray. - Re-enumerating lazy sequences repeatedly when caching is needed.
- Using descending logic incorrectly with positive step values.
Summary
- Use
Enumerable.Rangefor simple ascending contiguous sequences. - Use loop or projection for custom step sizes and descending patterns.
- Iterator methods with
yield returnprovide reusable sequence builders. - Decide between lazy and materialized sequences based on access pattern.
- Validate range and step assumptions to prevent subtle logic errors.

