Quick way to create a list of values in C#?
Categories:
Quick Ways to Create a List of Values in C#
Explore efficient methods for initializing and populating lists in C#, from basic constructors to collection initializers and LINQ.
In C#, a List<T>
is one of the most commonly used collection types for storing a dynamic array of objects. It provides a flexible way to manage collections where the size can change. This article will guide you through various quick and efficient methods to create and populate lists in C#, catering to different scenarios and preferences.
Basic List Initialization
The simplest way to create a List<T>
is by using its default constructor. This creates an empty list that you can then populate using the Add()
method. While straightforward, this approach can be verbose for initializing a list with multiple predefined items. You can also specify an initial capacity, which can be a minor optimization if you know the approximate number of items upfront, reducing reallocations.
using System.Collections.Generic;
public class BasicListExample
{
public static void Main()
{
// Create an empty list of strings
List<string> names = new List<string>();
// Add items individually
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");
// Create a list with an initial capacity (e.g., 5 items)
List<int> numbers = new List<int>(5);
numbers.Add(1);
numbers.Add(2);
}
}
Initializing an empty list and adding items individually.
List<T>
can slightly improve performance for very large lists by minimizing internal array reallocations, but it's often not necessary for smaller collections.Using Collection Initializers
Collection initializers provide a concise and readable syntax for creating and populating a List<T>
in a single statement. This is often the preferred method when you have a known set of items to add at the time of list creation. It significantly reduces boilerplate code compared to repeatedly calling Add()
.
using System.Collections.Generic;
public class CollectionInitializerExample
{
public static void Main()
{
// Initialize a list of strings using a collection initializer
List<string> fruits = new List<string>
{
"Apple",
"Banana",
"Cherry"
};
// Initialize a list of integers
List<int> primeNumbers = new List<int> { 2, 3, 5, 7, 11 };
}
}
Creating and populating lists using collection initializers.
Populating from Existing Collections with LINQ
When you need to create a List<T>
from an existing collection or sequence, LINQ (Language Integrated Query) offers powerful and expressive ways. The ToList()
extension method is particularly useful for converting any IEnumerable<T>
into a List<T>
. This is common when filtering, transforming, or projecting data from other data structures or query results.
using System.Collections.Generic;
using System.Linq;
public class LinqToListExample
{
public static void Main()
{
string[] arrayNames = { "David", "Eve", "Frank" };
// Convert an array to a list
List<string> nameList = arrayNames.ToList();
List<int> originalNumbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Filter and convert to a new list
List<int> evenNumbers = originalNumbers.Where(n => n % 2 == 0).ToList();
// Transform and convert to a new list
List<string> doubledStrings = originalNumbers.Select(n => (n * 2).ToString()).ToList();
}
}
Using ToList()
with LINQ to create lists from existing collections.
Flowchart of C# List creation methods.
ToList()
on very large collections, as it involves iterating and copying all elements into a new list, which can be an expensive operation.