0
0
C Sharp (C#)programming~20 mins

SelectMany for flattening in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Using SelectMany to Flatten Nested Lists
📖 Scenario: Imagine you have a list of classrooms, and each classroom has a list of students. You want to get a single list of all students from all classrooms combined.
🎯 Goal: Build a C# program that uses SelectMany to flatten a list of student lists into one list of all students.
📋 What You'll Learn
Create a list of classrooms where each classroom is a list of student names (strings).
Create a variable to hold all students flattened into one list using SelectMany.
Print the flattened list of all students.
💡 Why This Matters
🌍 Real World
Flattening nested collections is common when working with grouped data, like classrooms with students or departments with employees.
💼 Career
Understanding how to flatten collections with SelectMany is useful for data processing, reporting, and simplifying complex data structures in C# applications.
Progress0 / 4 steps
1
Create the nested list of classrooms
Create a variable called classrooms that is a List<List<string>> with exactly these three classrooms:
1. "Alice", "Bob"
2. "Charlie", "David"
3. "Eve", "Frank"
C Sharp (C#)
Need a hint?

Use List<List<string>> and initialize it with three inner lists of strings.

2
Add a variable to hold the flattened list
Create a variable called allStudents of type IEnumerable<string> but do not assign it yet.
C Sharp (C#)
Need a hint?

Use IEnumerable<string> to declare allStudents without assigning it yet.

3
Use SelectMany to flatten the classrooms
Assign allStudents to the result of using SelectMany on classrooms to flatten all inner lists into one sequence of strings.
C Sharp (C#)
Need a hint?

Use classrooms.SelectMany(classroom => classroom) to flatten the list.

4
Print the flattened list of all students
Use a foreach loop to print each student in allStudents on its own line.
C Sharp (C#)
Need a hint?

Use foreach (string student in allStudents) and Console.WriteLine(student) inside the loop.