Collections
Each type of collection has its unique characteristics and is suitable for specific scenarios. Here’s a brief overview of the most common types of collections and when to use them:
Commonly used collections
1. List
- Characteristics: An ordered collection of elements supports indexing.
- Use When: You need to maintain the order of elements, and you require frequent access by index. It is similar to an array but can dynamically resize.
- Example: Managing a list of students in a class.
2. HashSet
- Characteristics: Unordered collection of unique elements without index.
- Use When: You need to ensure that all elements are unique, and the order of elements doesn’t matter.
- Example: Keeping track of unique visitors to a website.
3. Dictionary
- Characteristics: Collection of key-value pairs, supports fast lookups by key.
- Use When: You need to associate values with keys and perform fast lookups, additions, and deletions based on keys.
- Example: Storing user profiles where the username is the key and the profile details are the value.
Examples to Illustrate Different Uses:
List Example:
List<string> students = new List<string>();
students.Add(“Alice”);
students.Add(“Bob”);
Console.WriteLine(students[0]); // Output: Alice
HashSet Example:
HashSet<int> uniqueNumbers = new HashSet<int>();
uniqueNumbers.Add(2);
uniqueNumbers.Add(1);
uniqueNumbers.Add(2); // Duplicate, will not be added
Console.WriteLine(uniqueNumbers.Count); // Output: 2
Dictionary Example:
// Example of a dictionary, a key-value pair collection
Dictionary<string, int> ageMap = new Dictionary<string, int>();
ageMap[“Alice”] = 25;
ageMap[“Bob”] = 30;
In a project scenario, let’s consider building a simple To-Do List application. This application will allow users to add tasks, remove tasks, and display the current list of tasks. This is a common requirement for productivity tools and can be easily managed using a List<T>.
Example: To-Do List Application
In this example, we’ll create a console application where users can manage their to-do list.
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
// Creating a list to store to-do tasks
List<string> toDoList = new List<string>();
while (true)
{
Console.WriteLine(“\nTo-Do List Application”);
Console.WriteLine(“1. Add Task”);
Console.WriteLine(“2. Remove Task”);
Console.WriteLine(“3. Display Tasks”);
Console.WriteLine(“4. Exit”);
Console.Write(“Choose an option: “);
int option = int.Parse(Console.ReadLine());
switch (option)
{
case 1:
Console.Write(“Enter a task to add: “);
string taskToAdd = Console.ReadLine();
toDoList.Add(taskToAdd);
Console.WriteLine(“Task added.”);
break;
case 2:
Console.Write(“Enter the task to remove: “);
string taskToRemove = Console.ReadLine();
if (toDoList.Remove(taskToRemove))
{
Console.WriteLine(“Task removed.”);
}
else
{
Console.WriteLine(“Task not found.”);
}
break;
case 3:
Console.WriteLine(“Current Tasks:”);
if
(toDoList.Count == 0)
{
Console.WriteLine(“No tasks in the list.”);
}
else
{
foreach (string task in toDoList)
{
Console.WriteLine(“- ” + task);
}
}
break;
case 4:
Console.WriteLine(“Exiting application.”);
return;
default:
Console.WriteLine(“Invalid option. Please try again.”);
break;
}
}
}
}
In a project scenario, let’s consider building a simple system to track unique visitors to a website. This application will allow us to add visitor IDs and ensure each ID is unique. This is a common requirement for web analytics and can be efficiently managed using a HashSet<T>.
Example: Unique Visitor Tracker
In this example, we’ll create a console application where visitor IDs are managed. We’ll be able to add visitor IDs and display the current set of unique visitor IDs.
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
// Creating a HashSet to store unique visitor IDs
HashSet<string> visitorIDs = new HashSet<string>();
while (true)
{
Console.WriteLine(“\nUnique Visitor Tracker”);
Console.WriteLine(“1. Add Visitor ID”);
Console.WriteLine(“2. Display Unique Visitor IDs”);
Console.WriteLine(“3. Exit”);
Console.Write(“Choose an option: “);
int option = int.Parse(Console.ReadLine());
switch (option)
{
case 1:
Console.Write(“Enter a visitor ID to add: “);
string visitorID = Console.ReadLine();
if (visitorIDs.Add(visitorID))
{
Console.WriteLine(“Visitor ID added.”);
}
else
{
Console.WriteLine(“Visitor ID already exists.”);
}
break;
case 2:
Console.WriteLine(“Unique Visitor IDs:”);
if (visitorIDs.Count == 0)
{
Console.WriteLine(“No visitor IDs in the set.”);
}
else
{
foreach (string id in visitorIDs)
{
Console.WriteLine(“- ” + id);
}
}
break;
case 3:
Console.WriteLine(“Exiting application.”);
return;
default:
Console.WriteLine(“Invalid option. Please try again.”);
break;
}
}
}
}
In a project scenario, let’s consider building a simple system to manage user profiles. This application will allow us to store user profiles with a unique username as the key and profile details as the value. This is a common requirement for applications that need to handle user data, and it can be efficiently managed using a Dictionary<TKey, TValue>.
Example: User Profile Manager
In this example, we’ll create a console application where user profiles can be added, retrieved, and displayed. Each profile will consist of a username (key) and user details (value).
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
// Creating a dictionary to store user profiles
Dictionary<string, string> userProfiles = new Dictionary<string, string>();
while (true)
{
Console.WriteLine(“\nUser Profile Manager”);
Console.WriteLine(“1. Add User Profile”);
Console.WriteLine(“2. Retrieve User Profile”);
Console.WriteLine(“3. Display All User Profiles”);
Console.WriteLine(“4. Exit”);
Console.Write(“Choose an option: “);
int option = int.Parse(Console.ReadLine());
switch (option)
{
case 1:
Console.Write(“Enter username: “);
string username = Console.ReadLine();
if (userProfiles.ContainsKey(username))
{
Console.WriteLine(“Username already exists. Try another.”);
}
else
{
Console.Write(“Enter user details: “);
string userDetails = Console.ReadLine();
userProfiles[username] = userDetails;
Console.WriteLine(“User profile added.”);
}
break;
case 2:
Console.Write(“Enter username to retrieve: “);
string userToRetrieve = Console.ReadLine();
if (userProfiles.TryGetValue(userToRetrieve, out string details))
{
Console.WriteLine($”User details for {userToRetrieve}: {details}”);
}
else
{
Console.WriteLine(“Username not found.”);
}
break;
case 3:
Console.WriteLine(“All User Profiles:”);
if (userProfiles.Count == 0)
{
Console.WriteLine(“No user profiles found.”);
}
else
{
foreach (var profile in userProfiles)
{
Console.WriteLine($”{profile.Key}: {profile.Value}”);
}
}
break;
case 4:
Console.WriteLine(“Exiting application.”);
return;
default:
Console.WriteLine(“Invalid option. Please try again.”);
break;
}
}
}
}
Task:
1. Basic Operations:
Write a C# program to create a HashSet<int> and perform basic operations such as adding, removing, and checking for the presence of elements.
2. Union and Intersection:
Given two HashSet<int> objects, use the UnionWith and IntersectWith methods to find the union and intersection of the sets.
3. Duplicate Removal:
Write a method that takes a list of integers as input and returns a new list with duplicates removed using a HashSet.
4. Subset and Superset:
Create two HashSet<int> objects and write a program to check if one set is a subset or superset of the other.
5. Set Difference:
Given two HashSet<int> objects, use the ExceptWith method to find the difference between the sets.
6. Basic Usage:
Write a C# program to create a Dictionary<string, int> to store and display the names and ages of people. Include adding, updating, and removing entries.
7. Key and Value Iteration:
Given a Dictionary<string, string> representing a phone book, iterate over the dictionary to print all names and their corresponding phone numbers.
8. Finding a Value by Key:
Write a method that takes a Dictionary<int, string> and an integer key as input and returns the corresponding value. If the key does not exist, return a default message.
9. Group by Property:
Given a list of objects of type Student with properties Name and Grade, create a Dictionary<int, List<Student>> to group students by their grade.
10. Frequency Count:
Write a program that takes a string and uses a Dictionary<char, int> to count the frequency of each character in the string.
11. Basic Operations:
Write a C# program to create a List<string> and perform basic operations such as adding, inserting, removing, and checking for the presence of elements.
12. Sorting:
Given a List<int>, write a method to sort the list in ascending and descending order.
13. Finding Elements:
Write a method that takes a List<string> and a string as input and returns all the indices where the string appears in the list.
14. Filtering:
Given a List<int>, write a method that returns a new list containing only the even numbers from the original list.
15. Conversion:
Write a program that converts an array of integers to a List<int> and performs some operations like reversing the list and finding the maximum and minimum values.