.NET
C#
programming
integers
code snippets

Populating a list of integers in .NET

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Populating a List<int> in .NET is simple, but the best approach depends on where the numbers come from. A fixed set of values, a generated numeric range, and integers parsed from text each call for slightly different patterns.

Start With Explicit Values

If the numbers are already known in source code, a collection initializer is the clearest option.

csharp
using System.Collections.Generic;

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

You can keep extending the list later with Add or AddRange.

csharp
numbers.Add(6);
numbers.AddRange(new[] { 7, 8, 9 });

This is the right style when the values are static and readability matters more than any abstraction.

Generate Values With a Loop

If the list is built at runtime, a loop is often the most direct answer.

csharp
1using System;
2using System.Collections.Generic;
3
4var evens = new List<int>();
5for (int i = 0; i <= 20; i += 2)
6{
7    evens.Add(i);
8}
9
10Console.WriteLine(string.Join(", ", evens));

A loop is especially useful when the rule is conditional or when each value depends on earlier computation.

Use Enumerable.Range for Straight Numeric Sequences

When the values form a simple contiguous range, LINQ is concise and expressive.

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5List<int> oneToTen = Enumerable.Range(1, 10).ToList();
6List<int> squares = Enumerable.Range(1, 5)
7    .Select(x => x * x)
8    .ToList();
9
10Console.WriteLine(string.Join(", ", squares));

Enumerable.Range is often more readable than a loop when the sequence itself is the main idea.

Parse Integers Safely From Text

A common real-world case is populating a list from CSV or user input. In that situation, int.TryParse is usually safer than int.Parse.

csharp
1using System;
2using System.Collections.Generic;
3
4string input = "10,20,30,not_number,40";
5var parsed = new List<int>();
6
7foreach (var token in input.Split(','))
8{
9    if (int.TryParse(token, out int value))
10    {
11        parsed.Add(value);
12    }
13}
14
15Console.WriteLine(string.Join(", ", parsed));

This keeps one bad token from turning the whole operation into an exception.

Set Capacity for Large Lists

If you know the approximate final size in advance, giving the list an initial capacity can reduce resizing overhead.

csharp
1int n = 1_000_000;
2var data = new List<int>(n);
3for (int i = 0; i < n; i++)
4{
5    data.Add(i);
6}

For small lists this rarely matters, but for large hot paths it can reduce allocations and make growth more predictable.

Arrays Versus Lists

There is also a small design choice hiding inside the question. If the collection size is fixed forever, an array may be simpler than List<int>. List<int> becomes the better choice when you need dynamic growth, AddRange, filtering pipelines, or general collection convenience.

That distinction helps keep the data structure aligned with the real usage pattern rather than with habit.

Combine Techniques When Needed

Real methods often mix these strategies. You might start with an initializer for a few fixed values, append a generated range, and then add validated integers from user input.

The main goal is not to find one universal pattern. It is to choose the pattern that makes the source of the numbers obvious.

Common Pitfalls

A common mistake is using int.Parse on untrusted input when one invalid token should not kill the whole operation.

Another issue is writing long LINQ expressions for sequences that would be clearer with a small loop.

Developers also sometimes forget to set capacity when they already know a very large final size, which causes avoidable internal resizing work.

Summary

  • Use collection initializers for small fixed integer sets.
  • Use loops for generated or conditional values.
  • Use Enumerable.Range when the numbers form a simple sequence.
  • Use TryParse when values come from text or external input.
  • Set capacity up front for large lists when the final size is known.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.