Collections

8. Collections#

An inventory report may need the day’s orders in sequence, a price looked up by product code, or a record of which customer IDs have already appeared. Arrays handle a fixed number of positions, but business data grows, shrinks, and is often found by key. This chapter shows you how to choose a container from the way your program finds its data, then makes List<T> and Dictionary<TKey, TValue> working tools: creating and updating them, looking up missing keys safely, counting and grouping records, and printing reports in a dependable order.

  • Collection families: Arrays, lists, dictionaries, and sets find data by position, by key, or by membership; stacks, queues, linked lists, and priority queues are previewed for later chapters.

  • Generics: Type parameters such as the T in List<T> let the compiler reject values of the wrong type.

  • List: A List<T> stores an ordered sequence that grows and shrinks without leaving holes.

  • Dictionary: A Dictionary<TKey, TValue> finds a value from a unique key, supports safe lookup, and drives counting and grouping.

  • Shared references: Two variables can name one collection, so a change through either one is visible through both.

Chapter Video

C# Collections Tutorial: Working with List, Hashset, Dictionary, and More! (25:09) by Coderversity.

Hosted on YouTube; property of its original creator, embedded here for educational reference only.

Learning Objectives

By the end of this chapter, you will be able to:

  1. Choose among an array, List<T>, Dictionary<TKey, TValue>, and HashSet<T> for a business task by asking whether the data is found by position, by key, or by membership, and whether its size changes.

  2. Read each collection call as a state change plus a returned result, and use generic type arguments so the compiler rejects values of the wrong type.

  3. Compare how lists, sets, and dictionaries answer Add, Remove, Contains, Count, and indexer requests, including the Try methods that report failure without throwing an exception.

  4. Create, fill, search, sort, and reverse a List<T>, apply the no-hole rule when removing items, and remove items safely during a loop with a backward loop or RemoveAll.

  5. Pass lists to methods and return new lists, explain when a change is visible to the caller because two variables share one list, and search, total, and sort a list of product records by a property.

  6. Look up dictionary entries safely with ContainsKey, TryGetValue, GetValueOrDefault, and TryAdd, and distinguish a stored zero from a missing key.

  7. Use a dictionary to count frequencies, total amounts by key, and group records in a dictionary of lists, and print the result in a dependable order with sorted keys.

  8. Choose key equality with a case-insensitive comparer, and explain why adding or removing a list item during foreach invalidates its enumerator.

Optional-reading outcome: filter, transform, order, count, and group collections with lambdas and LINQ, and decide when a query should be materialized.

Chapter Flow

Suggested three-meeting pace (115 minutes): read the relevant explanations and predict the selected example before class.

Meeting

Minutes

Guided focus

1

40

8.1 and 8.2: choosing a collection by position, key, or membership; reading operations as change plus result; generic type safety; and modification during foreach.

2

35

8.3: filling, removing without holes, searching, and sorting a list, then passing lists to methods and working with a list of product records.

3

40

8.4: key-value lookup, safe lookup of missing keys, frequency counts, sorted reports, grouping orders by customer, and case-insensitive keys.

Class uses selected traces, runs, and checks. Use the remaining worked examples for practice and reference. Supporting readings are selected separately; lab and homework follow the core lessons.

Glossary

#

Term

Explanation

1

Collection

An object that stores multiple values and provides operations for working with them.

2

Element

One item stored in a collection.

3

Access pattern

The way code most often finds its data: by position, by key, or by membership.

4

List

A resizable ordered collection accessed by index.

5

Collection initializer

Braces after new that fill a collection with starting values when it is created.

6

Dictionary

A collection that maps unique keys to values.

7

Key

A unique lookup value used to find an associated dictionary value.

8

Value

The data associated with a dictionary key.

9

Key-value pair

One dictionary entry, visited as a KeyValuePair<TKey, TValue> in a foreach loop.

10

Set

A collection of distinct elements used for membership tests.

11

Membership test

Asking whether a value is present, as Contains does for a set.

12

Stack

A collection whose most recently added item is removed first.

13

Queue

A collection whose earliest added item is removed first.

14

Linked list

A sequence organized as linked nodes rather than indexed positions.

15

Priority queue

A collection that selects the next item according to priority.

16

Collection operation

A call that may change a collection’s state and also returns a result, such as the bool from Remove.

17

Indexer

Square-bracket access, such as list[0] or prices["PEN"], that reads or assigns one element.

18

Generic type

A type written with a type parameter, such as List<T>.

19

Type parameter

A placeholder for the element type a generic collection stores.

20

Type argument

The actual type supplied for a type parameter, such as string in List<string>.

21

Type safety

The compiler’s guarantee that a collection receives only values of its declared element type.

22

Try method

A method such as TryGetValue or TryAdd that returns false instead of throwing when the request cannot succeed.

23

Count

The number of items currently stored in a collection.

24

Capacity

The number of items a list can hold before it must allocate a larger internal array.

25

Traversal

Visiting a collection’s elements, also called enumeration.

26

Enumerator

The object that tracks a foreach loop’s place and follows the collection’s rules for changes during traversal.

27

Alias

Another variable referring to the same collection object.

28

Snapshot

A separate copy of a collection’s elements taken at one moment, unaffected by later changes to the source.

29

Namespace

A named group of related types, such as System.Collections.Generic, brought into scope with using.

30

Fully qualified name

A type name written with its namespace, such as System.Collections.Generic.List<int>.

31

No-hole rule

A list keeps its elements in consecutive positions, so removing one shifts every later element down.

32

Linear search

Checking elements in order until a match is found or the list ends.

33

Lambda expression

A short unnamed function, such as p => p.Price > 20m, passed to methods like Find and RemoveAll.

34

In-place operation

An operation such as Sort or Reverse that rearranges the existing list instead of returning a new one.

35

Side effect

A change a method makes that the caller can observe, such as adding to a list it received.

36

Frequency count

A dictionary that maps each distinct item to the number of times it appears.

37

Grouping

Collecting records under a shared key, such as a dictionary that maps each customer to a list of orders.

38

Hash table

The structure a dictionary uses internally to find a key in expected constant time.

39

Equality comparer

A rule that decides whether two dictionary keys or set values count as equal, such as StringComparer.OrdinalIgnoreCase.

Lecture Slides

Chapter 8 lecture slides follow the current reading order. Supporting parts remain optional; instructor notes and editable decks are distributed separately.