C# New List With Values Tutorial – Complete Guide

Ever stumbled upon the need to initialize a list in C# with predefined values? Wondered how can you make this process simpler and more streamlined? We are here to bring you a step-by-step guide on how to create a new List in C# with values. A powerful feature of the C# programming language, understanding and mastering this can significantly enhance your coding skills and improve your game development process. So, let’s dive right in!

What is a List in C#?

A List is a collection of items, similar to an array. However, unlike an array, Lists in C# are dynamic and can grow and shrink automatically. This offers you greater flexibility when writing your code.

Why Initialize a C# List with Values?

Initializing a C# List with values lets you set up data structures quickly. Think of it as setting up the initial game state or the initial configuration of game elements. It helps get the program started off from a predefined state, rather than having to build it from scratch.

The Benefit of Learning this Technique

If this technique is something you tend to bypass, now is the time to reconsider. Understanding how to create a new C# list with values can drastically cut down your coding time, streamline your code, and let you handle more complex data structures more effortlessly. As we always say, knowledge is power – and there’s nothing like gaining more power over your coding craft!

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

How to Initialize a List in C# with Values?

Initializing a List in C# with values can be done at the time of declaration. Let’s walk through a few simple examples to illustrate this.

  
// Initialize a list with integers
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

In this example, we have created a List named numbers which holds integers. We have also initialized it with five numbers ‘1’, ‘2’, ‘3’, ‘4’, and ‘5’.

// Initialize a list with strings
List<string> names = new List<string> { "John", "Mike", "Sara" };

Here, we are creating a List of strings. This list, named names, is initialized with three names ‘John’, ‘Mike’, and ‘Sara’.

More Complex List Initializations

What if you want to initialize a list with more complex structures, such as objects and tuples? Let’s explore this with a couple of examples.

// Create a class
public class Player
{
    public string Name { get; set; }
    public int Score { get; set; }
}

// Initialize a list with objects
List<Player> players = new List<Player> {
    new Player() { Name = "Alex", Score = 100 },
    new Player() { Name = "Sam", Score = 200 }
};

In this snippet, we have created a new class ‘Player’. This class has two properties: ‘Name’ and ‘Score’. We then initialize a List with two Player objects, each with specific values for ‘Name’ and ‘Score’.

// Initialize a list with tuples
List<Tuple<string, int>> tupleList = new List<Tuple<string, int>> {
    new Tuple<string, int>("apple", 1),
    new Tuple<string, int>("banana", 2)
};

In this last example, we initialize a List of Tuples. Each Tuple in the list contains a string and an integer. We’ve initialized it with two tuples: ‘(“apple”, 1)’ and ‘(“banana”, 2)’.

Adding Values to a List

Beyond initialization, you can add new items to a List in C# dynamically. This can be done with the ‘Add’ method. Let’s understand this with the following examples.

// Declare an integer list
List<int> intList = new List<int>();

// Add values
intList.Add(10);
intList.Add(20);
intList.Add(30);

In this example, we declare an integer List named ‘intList’ and then add three values to it using the ‘Add’ method.

Adding Multiple Values at Once

You could even add a range of values at once to a list using the ‘AddRange’ method. Let’s have a look.

// Declare a string list
List<string> strList = new List<string>();

// Add range of values
strList.AddRange(new string[] { "abc", "def", "ghi" });

In this example, we create a string List ‘strList’ and add a range of string values to it using the ‘AddRange’ method.

Adding Lists Together

You can also add two lists together to create a new list. The ‘Concat’ method can be used for this purpose.

// Declare two integer lists
List<int> list1 = new List<int> { 1, 2, 3 };
List<int> list2 = new List<int> { 4, 5, 6 };

// Combine the two lists
List<int> combinedList = list1.Concat(list2).ToList();

In this example, we create two integer lists ‘list1’ and ‘list2’ and combine them into a new list named ‘combinedList’. The ‘Concat’ method is used to achieve this.

Working with Nested Lists

Initialising and adding values to nested lists is as easy as with simple lists. This allows you to handle more complex data structures easily.

// Initialize nested lists
List<List<string>> nestedList = new List<List<string>> 
{ 
    new List<string> { "Apple", "Banana" }, 
    new List<string> { "Cat", "Dog" } 
};

In this snippet, we initialize a nested list of strings. Each element of the outer list is another list of strings.

Useful List Methods in C#

Being aware of some useful List methods can make your life as a programmer easier. Here are some frequently used List functions:

  • Count: Returns the number of elements in the list.
  • Clear: Removes all elements from the list.
  • Contains: Checks if the list contains a certain value.
  • IndexOf: Returns the index of the first occurrence of a value in the list.
  • Remove: Removes the first occurrence of a specific object from the list.

Finding Elements in a List

Often, you might need to find the presence of an element in a list. The ‘Contains’ method can be used for this purpose. It returns a boolean value depending upon whether the element is found or not.

// Declare a list with values
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };

// Check for an item in the list
bool hasApple = fruits.Contains("Apple");
bool hasOrange = fruits.Contains("Orange");

In this example, ‘hasApple’ would return true because “Apple” is in the list. On the other hand, ‘hasOrange’ would return false because “Orange” is not in the list.

Removing Elements from a List

Removing elements from the list is a common operation. The ‘Remove’ method can help achieve this. It removes the first occurrence of a specific object from the list.

// Declare a list with values
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };

// Remove 'Banana' from the list
fruits.Remove("Banana");

In this snippet, “Banana” would be removed from the ‘fruits’ list.

Finding the Occurrence of an Element

You can find the index of the first occurrence of a specific object in a list using the ‘IndexOf’ method. It returns the zero-based index of the first occurrence of an item in the list or -1 if the item is not found.

// Declare a list with values
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };

// Find index of 'Banana'
int bananaIndex = fruits.IndexOf("Banana");

In this example, ‘bananaIndex’ would return 1. If we were to search for an item not found in the list, ‘IndexOf’ would return -1.

Clearing a List

The ‘Clear’ method is used to remove all elements from a List, leaving it empty. Observe the following example:

// Declare a list with values
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };

// Clear the list
fruits.Clear();

In this snippet, calling the ‘Clear’ method would empty the ‘fruits’ list.

Determining the Number of Elements in a List

Lastly, you can find the number of elements in a list using the ‘Count’ property. This is illustrated in the code snippet below:

// Declare a list with values
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };

// Get the count of elements in the list
int count = fruits.Count;

In this example, ‘count’ would return 3, because there are three elements in the list.

With these building blocks, you can effectively handle lists in C# and create intricate structures needed for your gaming or software projects. Happy coding!

Where to Go Next?

Having understood how to initialize a List with values in C#, it’s time to take your learning journey further.

We encourage you to apply this knowledge in Unity, an incredibly versatile game engine, that can help you create your own unique, engaging video games. Our Unity Game Development Mini-Degree by Zenva Academy, offers you a comprehensive curriculum covering all major aspects of game development. This includes designing game mechanics, creating dynamic audio effects, developing enemy AI, designing custom game assets, and much more. Unity’s versatility isn’t limited to game development, it can be applies to VR/AR projects and enterprise applications as well.

For those seeking a broader learning experience, our Unity Programming Curriculum has over 250 courses, offering a thorough understanding of game development with Unity, from basics to advanced concepts. With Zenva, you can progress from being an absolute beginner to a professional game developer. Happy learning and coding!

Conclusion

Understanding how to initialize and manage Lists in C# is an indispensable skill for any game developer. The power of Lists lies in their simplicity and flexibility, enabling you to handle increasingly complex data structures with ease and elegance. As you’ve seen, initializing a List with values in C# isn’t just an optimized coding practice, it opens up a world of possibilities for your game development prowess.

Want to put these techniques into action? Our Unity Game Development Mini-Degree will enable you to take your newly-acquired skills and transform the landscape of your game development journey. At Zenva, we strive to give you the-world class online education to develop your skills and cultivate your passion for game development. Start your journey with us today!

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.