.NET Collections
The .NET Framework provides a comprehensive set of classes for working with collections of objects. Collections are objects that group other objects. They offer a flexible way to manage groups of objects, allowing you to add, remove, search, and iterate through elements efficiently.
Introduction to Collections
Collections are fundamental to programming in .NET. They provide standardized ways to handle lists, dictionaries, sets, and more. The core namespace for collection types is System.Collections
and its generic counterpart System.Collections.Generic
.
Types of Collections
The .NET Framework offers various collection types, each suited for different scenarios:
Non-Generic Collections (System.Collections
)
These collections store elements as object
types. While flexible, they require casting and can lead to runtime errors if the types are not managed carefully. They are generally less preferred than generic collections for type safety.
ArrayList
: A dynamic array that can grow or shrink as needed.Hashtable
: A collection of key/value pairs.Queue
: A first-in, first-out (FIFO) collection.Stack
: A last-in, first-out (LIFO) collection.SortedList
: A collection of key/value pairs sorted by keys.
Generic Collections (System.Collections.Generic
)
Introduced with .NET 2.0, generic collections provide type safety by allowing you to specify the type of elements the collection will hold. This eliminates the need for casting and improves performance and code clarity.
Collection Type | Description | Common Use Case |
---|---|---|
List<T> |
A generic version of ArrayList , representing a strongly typed list of objects. |
Storing a dynamic list of items where order matters and duplicates are allowed. |
Dictionary<TKey, TValue> |
A generic version of Hashtable , storing key/value pairs. Keys must be unique. |
Mapping unique identifiers (keys) to related data (values), like retrieving user data by ID. |
HashSet<T> |
A collection that stores unique elements and provides high-performance set operations. | Ensuring a collection contains only unique items or performing set operations like union and intersection. |
Queue<T> |
A generic FIFO collection. | Processing tasks in the order they were received, like a print queue. |
Stack<T> |
A generic LIFO collection. | Managing operations that require undo functionality or processing items in reverse order. |
LinkedList<T> |
A doubly linked list, allowing efficient insertion and deletion of elements anywhere in the list. | Scenarios requiring frequent insertions/deletions in the middle of a sequence. |
Key Interfaces
Several interfaces define the behavior of collection types:
IEnumerable<T>
/IEnumerable
: Allows iteration over a collection.ICollection<T>
/ICollection
: Represents a strongly typed collection of objects.IList<T>
/IList
: Represents a strongly typed list of objects that can be accessed by index.IDictionary<TKey, TValue>
/IDictionary
: Represents a collection of key/value pairs.ISet<T>
: Represents a set of unique elements.
LINQ and Collections
Language Integrated Query (LINQ) provides powerful query capabilities for collections. You can perform filtering, sorting, projection, and aggregation operations directly on collection objects using a syntax similar to SQL.
using System.Collections.Generic;
using System.Linq;
// Sample list of integers
List<int> numbers = new List<int> { 1, 5, 2, 8, 3, 9, 4, 7, 6 };
// Find all numbers greater than 5
var greaterThanFive = numbers.Where(n => n > 5);
// Sort the numbers in ascending order
var sortedNumbers = numbers.OrderBy(n => n);
// Convert to an array
int[] numberArray = numbers.ToArray();
Console.WriteLine("Numbers greater than 5:");
foreach (var num in greaterThanFive)
{
Console.Write($"{num} ");
}
Console.WriteLine("\nSorted numbers:");
foreach (var num in sortedNumbers)
{
Console.Write($"{num} ");
}
Choosing the Right Collection
The choice of collection depends on your specific needs:
- For a simple list where order matters and duplicates are allowed:
List<T>
. - For fast lookups based on a key:
Dictionary<TKey, TValue>
. - To ensure uniqueness of elements:
HashSet<T>
. - For FIFO operations:
Queue<T>
. - For LIFO operations:
Stack<T>
.
Tip:
Always prefer generic collections (System.Collections.Generic
) over non-generic ones (System.Collections
) for improved type safety and performance.
Note:
The System.Linq
namespace provides extension methods that can be used with most collection types, significantly simplifying data manipulation.