Loops and returning lists

What a loop and a list are; serve collections.

1. What is this?

A loop repeats a block. A list (List<string>) holds many values in order. APIs often return lists as JSON: ["Ava","Liam"]. foreach walks a list one item at a time without an index.

2. Why do we use it?

Feeds, search results, and catalogues are lists served over HTTP.

3. Syntax breakdown

  • var names = new List<string> { "Ava", "Liam" };

    Creates a list of two strings. var infers the type.

  • foreach (var n in names) {

    Repeats once per item, calling it n each time.

  •   Console.WriteLine(n); }

    Prints each item on its own line.

5. Common mistakes

  • Forgetting using System.Collections.Generic; for List<T>.
  • Modifying a list while foreach walks it — collect changes and apply after.
  • Returning internal mutable lists directly from an API (copy or project first).

Practice task

Add "Noah" to the list and print all four names.

Hint

Add, "Noah" inside the { ... } initializer.

Try it below — tests run automatically when you press Run.

dotnet

Output

Press Run to see output.

Mini quiz

3 questions. Answer, then check.

  1. 1. What is a List<string>?

  2. 2. What does foreach do?

  3. 3. What do APIs often return for collections?

4. Example — edit and run

dotnet

Output

Press Run to see output.

Expected output: Ava