Collections and Lists
This section outlines how to use List<T>
and other collection types to manage lists of data in the application. Collections are essential for handling and manipulating sets of data in any .NET application.
List<T>
List<T>
is a generic collection type that provides a dynamic array implementation. It is a strongly-typed collection, meaning that it can only hold objects of the specified type.
Creating a List:
To create a new List<T>
instance, you can use the following syntax:
List<string> names = new List<string>();
Adding Items:
You can add items to a List<T>
using the Add
method:
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");
Accessing Items:
You can access individual items in a List<T>
using their index. Index starts at 0:
string first = names[0]; // "Alice"
Iterating through a List:
You can iterate through all items in a List<T>
using a foreach
loop:
foreach (string name in names)
{
Console.WriteLine(name);
}
Removing Items:
You can remove items from a List<T>
using the Remove
method:
names.Remove("Bob");
Finding Items:
You can find the index of an item in a List<T>
using the IndexOf
method:
int index = names.IndexOf("Charlie"); // 2
Other Methods:
List<T>
provides numerous other methods for working with collections:
Clear()
: Removes all items from the list.Contains(T item)
: Checks if an item exists in the list.Sort()
: Sorts the items in the list.Count
: Gets the number of items in the list.
Other Collections
Besides List<T>
, the .NET Framework offers a variety of other collection types:
Dictionary<TKey, TValue>
: Key-value pairs.HashSet<T>
: Unique items only.Queue<T>
: FIFO (First-In, First-Out) data structure.Stack<T>
: LIFO (Last-In, First-Out) data structure.SortedSet<T>
: Sorted collection of unique items.
Example Usage
Here’s an example of using List<T>
to store and manage a list of customers:
using System.Collections.Generic;
class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Customer> customers = new List<Customer>();
customers.Add(new Customer { Id = 1, Name = "Alice" });
customers.Add(new Customer { Id = 2, Name = "Bob" });
customers.Add(new Customer { Id = 3, Name = "Charlie" });
// Print all customers
foreach (Customer customer in customers)
{
Console.WriteLine($"ID: {customer.Id}, Name: {customer.Name}");
}
// Find customer by ID
Customer found = customers.Find(c => c.Id == 2);
if (found != null)
{
Console.WriteLine($"Found customer: ID: {found.Id}, Name: {found.Name}");
}
}
}
This example demonstrates how to use List<T>
to create a collection of custom objects and perform common operations on them.