Mastering Collections in .NET - A Complete Guide with Code Examples

Collections in .NET are essential for managing groups of objects efficiently. They provide a way to store, retrieve, and manipulate data structures in a systematic manner. In .NET there are various types of collections available, each serving different purposes and offering unique functionalities.

They provide functionalities for adding, removing, and manipulating items within the collection. This article dives into the essentials of collections in .NET, covering their types and usage with detailed C# examples.

Collections in .NET

Types of Collections
  • Arrays
  • ArrayList
  • Lists
  • SortedList
  • Dictionaries
  • Tuples
  • Hastable
  • HasSets
  • Sorted Sets
  • Stacks
  • Queues
  • Linked Lists 
  • Observable Collections 
  • and, more.

Arrays

Arrays are the simplest form of collections in .NET. They offer fixed-size storage for elements of the same type. Arrays provide fast access to elements using indexes but lack dynamic resizing capabilities.
string[] names = new string[3]; // Array of 3 strings
int[] numbers = new int[5] { 1, 2, 3, 4, 5 }; // Initializer syntax
Elements are accessed via zero-based index:
string second = names[1]; numbers[0] = 5; // Update 1st element
Built-in array features include Length property, handy utility methods like Sort, Fill, Copy, and Resize for multidimensional arrays.

Common operations like iteration can be done with for/foreach loops:
foreach (int n in numbers) 
    Console.WriteLine(n);
ArrayList
 
ArrayList is a dynamic sized collection of objects that handles the sizing and allocation internally to easily grow and add items on demand.

As a non-generic collection, ArrayLists can contain elements of any type together:
ArrayList list = new ArrayList();
list.Add(25); //int number 
list.Add("Hello"); //string added
Elements are accessed via index like arrays:
int num = (int)list[0];
string s = (string)list[1];
Common operations revolve around Inserting, Accessing, and Removing items:
list.Insert(1, "World"); // Insert mid-way
 
list.Remove("Hello"); // Remove by value
list.RemoveAt(0); // Remove by index
ArrayLists are helpful for collecting objects before converting to an array or binding to a UI list.

Limitation is no type safety since any object can be added.

Lists 

The List collection allows storage of strongly-typed objects in an ordered way that provides fast indexing and traversal. Lists declare the contained type in angle brackets and initialize either empty or with values:
List<stringnames = new List<string>();
List<intnumbers = new List<int> { 1, 2, 3, 4 };
Common operations include Add to insert items, Remove and Clear to delete items, Contains and IndexOf to search, Sort to order items, etc:
names.Add("Sarah"); names.Sort();
bool hasTom = names.Contains("Tom");
SortedList
 
The SortedList class provides a dynamically sized collection of key/value pairs that are automatically sorted by key based on either string or numeric ordering rules.

Since it is indexed by key, retrieval times are very fast regardless of ordering.

Initialization looks similar to a dictionary, without specifying types:
SortedList list = new SortedList();
list.Add("b""banana");
list.Add("a""apple"); // will be sorted to the first position
Values are retrieved by specifying the key:
string fruit = (string)list["a"]; //apple
The sorting capability makes a SortedList useful for maintaining objects in a certain order for quick sorted iterations.

Dictionaries 

Dictionaries contain key/value pairs that allow efficient lookup of values given a known key. The key and value types are declared in angle brackets upon initialization:
Dictionary<stringintages = new Dictionary<stringint>(); 
ages.Add("Sara", 31); // Insert key and value
ages["Tom"] = 42; // Another insert way
Accessing values requires passing the key:
int saraAge = ages["Sara"];
Common operations include adding/updating values, removing keys, checking if a key exists, enumeration over keys or values.

Tuples 

Tuples represent a lightweight way to temporarily group values together without needing a formal class definition. Specify types for each component in angle brackets:
(string Name, int Age) customer = ("Bob", 42);
Access is by position instead of name:
int age = customer.Item2; // Age is 2nd item
Tuples are immutable - contents cannot be modified after creation. Common uses cases include returning multiple values from a method and grouping ad hoc sets of data.

Hashtable 

Hashtable is a non-generic dictionary-like collection that stores key/value pairs in a bucket hash structure allowing efficient lookups.

Being non-generic, keys and values can be of any object type mixed together:
Hashtable table = new Hashtable();
table.Add("age", 30); // int value 
table.Add("name""John"); // string value
Values are accessed by passing the key:
int age = (int)table["age"];
Common operations include, Adding/Retrieving elements by key, Removing keys, Checking if keys or values are present, Iterating through keys/values
table.Remove("age");
bool hasName = table.ContainsKey("name");
 
foreach (string key in table.Keys)
{
    //your logic here
}
Hashtables are useful when you require a dictionary but don't need type safety. Performance is very fast due to the internal hashing.

HashSets 

Sets represent unique unordered collections. Common types are HashSet and SortedSet. Sets declare the contained type on initialization:
HashSet<intnumbers = new HashSet<int>();
Items can be added, removed, and checked for containment:
numbers.Add(1); 
numbers.Add(2); 
numbers.Remove(1); 
bool containsTwo = numbers.Contains(2);
Key capabilities include very fast lookups, ensuring uniqueness, intersections/unions with other sets.

Sorted Sets 

SortedSets automatically keep their elements ordered without manually calling a sort method. Typical implementation SortedSet<T> takes a generic type.
SortedSet<intnumbers = new SortedSet<int>(); 
numbers.Add(3); 
numbers.Add(1); // 1, 3
You can customize ordering rules via an extra parameter in constructors.

Stacks

Stacks are last-in, first-out (LIFO) ordered collections. Stacks do not declare a type:
Stack stack = new Stack();
Push adds items to the top, Pop removes items from the top:
stack.Push("first"); 
stack.Push("second"); 
string second = stack.Pop(); // Returns "second"
Key functions include Peek at top item without removing, Contains and Count checks, and Clearing out the entire stack.

Queues

Queues implement first-in, first-out (FIFO) ordering for stored items. Queues are declared and created without any type parameters:
Queue queue = new Queue();
Enqueue adds items to the back, Dequeue removes items from the front:
queue.Enqueue("first"); queue.Enqueue("second"); 
string first = queue.Dequeue(); // Returns "first"
Key queue capabilities include peeking at next item, checking count, clearing all entries.

Linked Lists 

LinkedLists store items in a doubly-linked node structure. This allows efficient insertion and removal from any point without shifting other items.
LinkedList<stringlinks = new LinkedList<string>();
Adding and removing items does not require indexes. New nodes are inserted relative to existing ones:
links.AddFirst("first"); 
links.AddLast("second"); 
links.Remove("first");
Linked lists enable very fast constant-time insertions and deletions from interior points via the linked node structure.

Observable Collections 

ObservableCollection is a list that automatically fires notifications anytime items get added, removed, or the whole list is refreshed.

Usage works just like a regular List, but UI controls like ListBox will update automatically:
ObservableCollection<stringitems = new ObservableCollection<string>(); 
items.Add("Item 1"); // UI will update
Conclusion

This makes databinding lists to UI controls very simple. Just point the control to an observable collection instance.

By understanding and utilizing these different types of collections in .NET, you can optimize your code for better performance and efficiency. Experiment with these examples and explore more advanced features to enhance your development skills.

With this detailed article on collections in .NET along with practical code examples in C#, you are well-equipped to leverage the power of collections effectively in your projects. Happy coding!

No comments:

Powered by Blogger.