C# Collections
In C#, a collection is a group of related objects that can be manipulated as a single unit. .NET provides several built-in collection types, including lists, arrays, and dictionaries. In this tutorial, we'll discuss how to use collections in C#.
Syntax
The syntax for using collections in C# varies depending on the collection type. Here are a few examples:
// Creating a List<T> object
List<int> numbers = new List<int>();
// Adding elements to a List<T>
numbers.Add(10);
numbers.Add(20);
numbers.Add(30);
// Creating an array
int[] array = new int[3];
// Creating a dictionary
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Alice", 25);
ages.Add("Bob", 30);
ages.Add("Charlie", 35);
Example
Let's say we want to create a program that stores the names of a list of students and their corresponding grades. We could use a dictionary to associate each student's name with their grade:
Dictionary<string, int> grades = new Dictionary<string, int>();
grades.Add("Alice", 85);
grades.Add("Bob", 90);
grades.Add("Charlie", 80);
foreach (var item in grades)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
Output
When we run the example code above, the output will be:
Alice: 85
Bob: 90
Charlie: 80
This is because we used a dictionary to map each student's name to their grade and printed out the results using a foreach loop.
Explanation
In the example above, we used a dictionary to store the names and grades of a list of students. We then used a foreach loop to iterate over the dictionary and print out each student's name and grade.
Use
Collections are useful when you need to manipulate groups of related objects as a single unit. You can use collections to store data, iterate over elements, and perform various operations on them.
Important Points
- Collections are reference types and memory is allocated dynamically.
- Different collection types have different performance and memory characteristics.
- You can sort, filter, and perform various operations on collections using LINQ.
Summary
In this tutorial, we discussed how to use collections in C#. We covered the syntax, example, output, explanation, use, and important points of collections in C#. With this knowledge, you can now use collections in your C# code to store and manipulate groups of related objects as a single unit.