Sobes.tech
Senior

What data structures (containers) do you know in C#? When to use which?

sobes.tech AI

Answer from AI

In C#, there are several fundamental data structures:

  • List<T> — a dynamic array suitable for storing ordered data with fast access by index.
  • Dictionary<TKey, TValue> — a hash table for quick key-based lookup.
  • HashSet<T> — a set of unique elements, efficient for checking the presence of an item.
  • Queue<T> — a FIFO queue, where the order of processing is important.
  • Stack<T> — a LIFO stack, for reverse order processing.
  • LinkedList<T> — a doubly linked list, convenient for frequent insertions and deletions in the middle of the collection.

The choice depends on the task: if fast access by index is needed — List; if searching by key — Dictionary; if uniqueness — HashSet; if order of processing — Queue or Stack.

Example of using Dictionary:

var dict = new Dictionary<string, int>();
dict["apple"] = 3;
if (dict.ContainsKey("apple")) {
    Console.WriteLine(dict["apple"]); // 3
}