Junior
What collections do you know in C#?
sobes.tech AI
Answer from AI
In C#, there are several categories of collections:
-
Non-generic: Work with the
objecttype and require casting.ArrayList- dynamic array.Hashtable- key-value pair collection based on hash table.Stack- stack collection (LIFO).Queue- queue collection (FIFO).SortedList- key-value pair collection sorted by key.
-
Generic: Provide type safety and better performance.
List<T>- type-safe dynamic array.Dictionary<TKey, TValue>- type-safe key-value pair collection based on hash table.Stack<T>- type-safe stack collection (LIFO).Queue<T>- type-safe queue collection (FIFO).HashSet<T>- collection of unique elements without a specific order.SortedList<TKey, TValue>- type-safe key-value pair collection sorted by key.SortedDictionary<TKey, TValue>- type-safe key-value pair collection sorted by key in the form of a binary search tree.LinkedList<T>- doubly linked list.
-
Thread-safe: For use in multithreaded environments.
ConcurrentBag<T>- unordered thread-safe collection of elements.ConcurrentDictionary<TKey, TValue>- thread-safe dictionary.ConcurrentQueue<T>- thread-safe queue (FIFO).ConcurrentStack<T>- thread-safe stack (LIFO).BlockingCollection<T>- implements blocking add and take operations.
-
Specialized:
ObservableCollection<T>- collection that notifies about changes (for data binding).BitArray- compact representation of bits.NameValueCollection- collection of key-value pairs, keys are not unique.
Most of them implement various interfaces such as IEnumerable, ICollection, IList, IDictionary.
Example of using List<T>:
// Creating a list of strings
using System.Collections.Generic;
List<string> names = new List<string>();
// Adding elements
names.Add("Alice");
names.Add("Bob");
names.Add("Charlie");
// Accessing an element
string firstPerson = names[0]; // Alice
// Removing an element
names.Remove("Bob");
// Iterating over the list
foreach (string name in names)
{
// Do something with name
}
Example of using Dictionary<TKey, TValue>:
// Creating a dictionary
using System.Collections.Generic;
Dictionary<int, string> students = new Dictionary<int, string>();
// Adding elements
students.Add(101, "Alice");
students.Add(102, "Bob");
// Accessing an element by key
string studentName = students[101]; // Alice
// Checking if a key exists
if (students.ContainsKey(103))
{
// Key exists
}
// Iterating over the dictionary
foreach (KeyValuePair<int, string> student in students)
{
// Access student.Key and student.Value
}