Collections in C#
C# provides a rich set of collection classes to handle groups of related objects. These collections offer various ways to store, manage, and manipulate data efficiently.
Arrays:
Fixed size.
Fast access to elements by index.
Example:
code
using System;
namespace NationalParks
{
class Program
{
static void Main(string[] args)
{
string[] parks = { "Yellowstone", "Yosemite", "Zion", "Grand Canyon" };
foreach (var park in parks)
{
Console.WriteLine(park);
}
}
}
}
Lists:
Dynamically sized.
Provides methods to add, remove, and search elements.
Example:
code
using System;
using System.Collections.Generic;
namespace NationalParks
{
class Program
{
static void Main(string[] args)
{
List<string> parks = new List<string> { "Yellowstone", "Yosemite", "Zion", "Grand Canyon" };
parks.Add("Great Smoky Mountains");
parks.Remove("Zion");
foreach (var park in parks)
{
Console.WriteLine(park);
}
}
}
}
Dictionaries:
Key-value pairs.
Fast lookup by key.
Example:
code
using System;
using System.Collections.Generic;
namespace NationalParks
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> parkEstablishments = new Dictionary<string, int>
{
{ "Yellowstone", 1872 },
{ "Yosemite", 1890 },
{ "Grand Canyon", 1919 }
};
parkEstablishments["Great Smoky Mountains"] = 1934;
foreach (var park in parkEstablishments)
{
Console.WriteLine($"{park.Key} was established in {park.Value}");
}
}
}
}
HashSet:
Unordered collection of unique elements.
Fast lookup and insertion.
Example:
code
using System;
using System.Collections.Generic;
namespace NationalParks
{
class Program
{
static void Main(string[] args)
{
HashSet<string> parks = new HashSet<string> { "Yellowstone", "Yosemite", "Zion", "Grand Canyon" };
parks.Add("Great Smoky Mountains");
parks.Remove("Zion");
foreach (var park in parks)
{
Console.WriteLine(park);
}
}
}
}