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
TinList<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:
Choose among an array,
List<T>,Dictionary<TKey, TValue>, andHashSet<T>for a business task by asking whether the data is found by position, by key, or by membership, and whether its size changes.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.
Compare how lists, sets, and dictionaries answer
Add,Remove,Contains,Count, and indexer requests, including theTrymethods that report failure without throwing an exception.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 orRemoveAll.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.
Look up dictionary entries safely with
ContainsKey,TryGetValue,GetValueOrDefault, andTryAdd, and distinguish a stored zero from a missing key.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.
Choose key equality with a case-insensitive comparer, and explain why adding or removing a list item during
foreachinvalidates 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 |
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 |
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 |
10 |
Set |
A collection of distinct elements used for membership tests. |
11 |
Membership test |
Asking whether a value is present, as |
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 |
17 |
Indexer |
Square-bracket access, such as |
18 |
Generic type |
A type written with a type parameter, such as |
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 |
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 |
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 |
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 |
30 |
Fully qualified name |
A type name written with its namespace, such as |
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 |
34 |
In-place operation |
An operation such as |
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 |
Lecture Slides
Chapter 8 lecture slides follow the current reading order. Supporting parts remain optional; instructor notes and editable decks are distributed separately.