Using C#, generic collections such as `Dictionary` and `List` are widely used for managing data efficiently. Here’s an example of using both `Dictionary` and `List`:
Using Dictionary:
A `Dictionary<TKey, TValue>` is a collection of key-value pairs, where each key must be unique.
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { // Creating a dictionary to store student IDs and their corresponding names Dictionary<int, string> studentDictionary = new Dictionary<int, string>(); // Adding items to the dictionary studentDictionary.Add(1, "Alice"); studentDictionary.Add(2, "Bob"); studentDictionary.Add(3, "Charlie"); // Accessing items in the dictionary Console.WriteLine("Name of student with ID 2: " + studentDictionary[2]); // Iterating over dictionary entries foreach (var kvp in studentDictionary) { Console.WriteLine($"ID: {kvp.Key}, Name: {kvp.Value}"); } } }
Using List:
A `List<T>` is a dynamic array that can hold elements of a specified type `T`.
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { // Creating a list to store integers List<int> numberList = new List<int>(); // Adding items to the list numberList.Add(10); numberList.Add(20); numberList.Add(30); // Accessing items in the list Console.WriteLine("Second number in the list: " + numberList[1]); // Iterating over list elements foreach (var num in numberList) { Console.WriteLine("Number: " + num); } } }
Using List of Dictionaries:
You can also use a `List<Dictionary<TKey, TValue>>` to store a collection of dictionaries.
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { // Creating a list of dictionaries to store employee information List<Dictionary<string, object>> employeeList = new List<Dictionary<string, object>>(); // Adding dictionaries to the list employeeList.Add(new Dictionary<string, object> { {"Name", "Alice"}, {"Age", 30}, {"Department", "HR"} }); employeeList.Add(new Dictionary<string, object> { {"Name", "Bob"}, {"Age", 35}, {"Department", "IT"} }); // Accessing items in the list of dictionaries foreach (var employee in employeeList) { Console.WriteLine($"Name: {employee["Name"]}, Age: {employee["Age"]}, Department: {employee["Department"]}"); } } }
These examples illustrate the basic usage of `Dictionary` and `List` in C#. Depending on your requirements, you can leverage these collections to efficiently manage your data.