C# List Tutorial – Complete Guide

First off, let’s dive into one of the most versatile structures that C# offers – the C# List. As part of any programmer’s toolkit, understanding and mastering lists can add an extra layer of sophistication to your projects, be it a simple app or an intricate game. As we delve into this subject together, expect to find it accessible, valuable and immeasurably useful.

What is C# List?

A C# List is a part of the System.Collections.Generic namespace and it is a type of dynamic array. Unlike traditional arrays in C#, the size of a List can be modulated during runtime. This means you can add, remove, and query items in the List while your program is running.

What is it for?

Lists are lynchpin structures in coding and are extensively used. They are instrumental in scenarios where you have to deal with a collection of items and the number of these items could change over time. For instance, think of an inventory system in a game where players can pick up or drop items.

Why Should You Learn It?

Mastering Lists in C# opens up a plethora of possibilities, particularly in game development scenarios. Aside from the dynamic flexibility it offers, lists are capable of storing different types of elements including custom classes and structures. By being adept at using Lists, you can design more complex and interactive scenarios in your games or applications. With this powerful asset in your toolbox, your potential to create efficient and improved code is abundant.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Creating a List in C#

Creating a List in C# is simple. It is done by declaring a new List variable and specifying the type of elements you want to store.

List numbers = new List();

In this case, the List ‘numbers’ will hold integer values. But the List can store other types of elements too, such as strings:

List names = new List();

Adding Elements to a List

To add elements to a List, you utilize the ‘Add’ method.

numbers.Add(1);
numbers.Add(2);
numbers.Add(3);

names.Add("Alice");
names.Add("Bob");

When you add elements, they get appended to the end of the List. So the ‘numbers’ List will look like so: {1, 2, 3} and ‘names’ List will look like: {“Alice”, “Bob”}.

Iterating Over a List

To cycle through each element in a List, you can use a simple for-each loop.

foreach(int number in numbers) 
{
    Console.WriteLine(number);
}

foreach(string name in names) 
{
    Console.WriteLine(name);
}

Both codes output the elements stored in the lists ‘numbers’ and ‘names’.

Removing Elements from a List

To remove an element from a List, we make use of the ‘Remove’ method.

numbers.Remove(1);

names.Remove("Alice");

In both cases, the respective elements 1 and “Alice” will be removed from their Lists.

Finding Elements in a List

To determine if an element exists within a List, you can employ the ‘Contains’ method. This method returns a boolean value – true when the element is found, and false otherwise.

if(numbers.Contains(2)) 
{
    Console.WriteLine("2 exists in the list");
}

if(names.Contains("Bob")) 
{
    Console.WriteLine("Bob exists in the list");
}

If the element is found in the respective List, it prints a message to indicate that.

Manipulating Lists Using LINQ

Language Integrated Query (LINQ) is an integral part of C# that makes querying and manipulating data from Lists possible.

Let’s say you want to find all even numbers in ‘numbers’ List. You can accomplish it like this:

List evenNumbers = numbers.Where(n => n % 2 == 0).ToList();

In this line of code, the ‘Where’ clause filters the ‘numbers’ List to include only the elements (represented as ‘n’) where ‘n % 2 == 0’ is true (in other words, even numbers). The ‘ToList()’ function then converts the selection to a new List.

Similarly, if you want to get all the names in ‘names’ List that have a length greater than 3, you can do it as follows:

List longNames = names.Where(n => n.Length > 3).ToList();

In this case, ‘Where’ is used to filter the ‘names’ List using the condition ‘n.Length > 3’, and ‘ToList()’ is used to create a new List from the selection.

Sorting Lists

Sorting a List can be done with the ‘Sort’ method.

numbers.Sort(); // sorts the list in ascending order of the numbers

names.Sort(); // sorts the list alphabetically

After these lines, both Lists will hold their respective elements in ascending order.

In essence, by harnessing the power of C# Lists, you can manage collections of data in your code more effectively and flexibly, multiplying the possibilities of what you can create. We at Zenva believe that mastering this fundamental construct is a crucial step in broadening your programming and game development capabilities.

Accessing Elements in a List

To get the value of a specific element in a List, you use the index of that element. Remember that indexes in Lists (like in arrays) start at 0.

int firstNumber = numbers[0]; // 1st element
string firstPerson = names[0]; // 1st element

First element of numbers and names can be retrieved with these lines of code.

Counting Elements in a List

It’s also possible to determine the number of elements in a List using the ‘Count’ property, which is quite handy.

int numberOfNumbers = numbers.Count;
int numberOfNames = names.Count;

These lines output the number of elements in ‘numbers’ and ‘names’ respectively.

Lists of Custom Objects

Lists are quite versatile, capable of storing objects of custom classes and structures. Let’s consider an example of a List that stores objects of a custom person class.

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

List people = new List();
people.Add(new Person { Name = "Alice", Age = 25 });
people.Add(new Person { Name = "Bob", Age = 30 });

In this example, we define a custom class ‘Person’ and create a List named ‘people’ that holds objects of this class. Then we add two people to the list.

Querying Lists of Custom Objects

Continuing with the above example, we can use LINQ to query the ‘people’ List. Suppose you want to find all persons older than 25, it would look something like this:

List oldPeople = people.Where(p => p.Age > 25).ToList();

In this code, ‘Where’ is used to filter the ‘people’ List where ‘p.Age > 25’, and ‘ToList()’ is used to create a new List from the selection.

Modifying Elements in a List

In Lists, you can modify an element directly using its index.

numbers[0] = 100; // changes the 1st element to 100

names[0] = "Carol"; // changes the 1st element to "Carol"

After these lines, the first elements of ‘numbers’ and ‘names’ will be updated to 100 and “Carol” respectively.

Clearly, C# Lists offer the opportunity to proficiently handle data collections, making the code cleaner and more efficient. Regardless of the magnitude or nature of programming projects you tackle, mastering Lists could significantly enhance your problem-solving approach. As we at Zenva continue to delve into C# List intricacies, we encourage you to further apply and explore more of its diverse functionalities.

Where to go next?

Having delved into the depths of C# Lists, you’re now equipped with an essential tool that will significantly enhance your coding capabilities. However, the world of programming is vast and profound, it doesn’t stop at Lists. The next logical step in your journey of learning would be to apply your knowledge in expansive, practical projects such as game development.

At Zenva, we continue to provide a wide array of beginner to professional courses, including learing coding, game creation, AI and more. One of our key offerings is the Unity Game Development Mini-Degree. This comprehensive collection of courses uses one of the most popular game engines, Unity, to impart the skills needed for game development, touching on diverse areas such as game mechanics, audio effects, animation, and more. Unity is a preferred choice of both AAA and indie developers and has a wide range of applications beyond gaming.

So, don’t let your learning journey stop here. Check out our Unity courses and continue expanding your horizons. With Zenva, you have the potential to go from beginner to professional, opening up a world of opportunities. Happy coding!

Conclusion

Harnessing the power of versatile C# Lists can revolutionize how you manage collections of data, elevating your coding skills and broadening your ability to create more complex projects. But Lists is only one stepping stone to mastering programming. The world of game development and other exciting fields are waiting to be explored, bringing more sophistication and depth to your creative potential.

We at Zenva invite you to embark on a journey of mastery and success in C#, game development and many more. Accompany us as we delve into the depths of coding and game creation through our comprehensive platform, such as the Unity Game Development Mini-Degree. Endeavor to make an impact in the vibrant digital world as you transform from an amateur explorer to a proficient creator with us.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.