Lists are dynamic arrays that can grow or shrink in size dynamically as elements are added or removed.
List in C#
In C#, List is a generic collection type provided by the .NET framework. It belongs to the System.Collections.Generic namespace. Before dive into C# List you should think about the following:
-
Generic Type: List is a generic type, which means it can hold elements of a specified type. For example, List<int> represents a list that can hold integers, while List<string> represents a list that can hold strings etc.
-
Dynamic Size: Unlike arrays, which have a fixed size once created, lists can dynamically adjust their size as elements are added or removed. This makes them more flexible and convenient for scenarios where the size of the collection may change over time.
-
Indexed Access: Elements in a list are accessed using zero-based indexing. You can access elements by their index using the square bracket notation, e.g., list[0] to access the first element.
-
Add and Remove Elements: Lists provide methods to add (Add) and remove (Remove, RemoveAt) elements. You can add elements to the end of the list or insert them at a specific position. Similarly, you can remove elements by their value or index.
-
Enumeration: Lists can be easily enumerated using foreach loops or LINQ queries. This allows you to iterate over all elements in the list and perform operations on them.
-
Performance: Lists provide fast access to elements by index, similar to arrays. However, inserting or removing elements in the middle of the list can be slower compared to adding or removing elements at the end, as it may require shifting other elements.
A simple example to show the basic usage of List, including creating a list, adding elements, accessing elements by index, and iterating over all elements in the list with a foreach loop.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create a list of strings
List<string> fruits = new List<string>();
// Add elements to the list
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Orange");
// Access elements by index
Console.WriteLine(fruits[0]); // Output: Apple
// Iterate over all elements in the list
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
// Output:
// Apple
// Banana
// Orange
}
}
Getting the List of another List in C#
In the following example we start by creating a console application using Visual Studio 2022:

I call my console app "ListOfList":

and press the Next button:

By the time I create this console application I am using .NET 8:

and press the Create button:

I create a function named GetStatesAndCities: and inside of it I want to have a list of States with their Cities I start by specifying the type of the list, note that I want a list that can hold a list of strings, the name of the list being declared, and initializes a new instance of the object using the new keyword:
// the long form:
List<List<string>> states = new List<List<string>>();
// you can also use:
var states = new List<List<string>>();
// a simplify form:
List<List<string>> states = new();
// a more simplify form (with C# 12):
List<List<string>> states = [];
Here is my function where I add the states and cities list:
static void GetStatesAndCities()
{
List<List<string>> states = [];
states.Add(new List<string> {
"Florida", "Miami", "Orlando", "Tampa", "Jacksonville", "Fort Lauderdale", "Tallahassee", "Key West", "Naples", "Pensacola", "Sarasota"
});
states.Add(new List<string> {
"New York", "New York City", "Buffalo", "Rochester", "Albany", "Syracuse", "Yonkers", "White Plains", "Ithaca", "Utica", "Niagara Falls"
});
states.Add(new List<string> {
"California", "Los Angeles", "San Francisco", "San Diego", "Sacramento", "San Jose", "Oakland", "Fresno", "Long Beach", "Anaheim", "Santa Monica"
});
states.Add(new List<string> {
"Illinois", "Chicago", "Springfield", "Peoria", "Rockford", "Aurora", "Naperville", "Champaign", "Bloomington", "Joliet", "Evanston"
});
states.Add(new List<string> {
"Texas", "Houston", "Dallas", "Austin", "San Antonio", "Fort Worth", "El Paso", "Arlington", "Corpus Christi", "Plano", "Lubbock"
});
// iterrate through the state to what we want
for (int i = 0; i < states.Count; i++)
{
// only get the States name (the 1rst item in each list)
var state = states[i];
Console.WriteLine(state[0]);
}
}
When you call this fuction you should ended up with the following result:

Now I I want to access the cities for each state I can update my for loop by adding another for loop like so:
// iterrate through the state to what we want
for (int i = 0; i < states.Count; i++)
{
// only get the States name (the 1rst item in each list)
var state = states[i];
Console.WriteLine(state[0]);
// get the cities
for (int j = 1; j < state.Count; j++)
{
Console.WriteLine($" --> {state[j]}");
}
}
Now the result should look like this:

who discovers this article may wonder if I have never heard of foreach with a smile 
So I reassure you, you can have the same result with a foreach loop here is the proof:
foreach (var state in states)
{
// Get the state name (the first item in each list)
Console.WriteLine(state[0]);
// Get the cities
foreach (var city in state.Skip(1)) // Skip the first item (state name)
{
Console.WriteLine($" --> {city}");
}
}
Ouf! Hope you got the idea.
I hope you enjoyed this little reading, I promise to bring you even more tutorials, so until now, good practice and happy codding!
No comments