C# > Core C# > Control Flow > foreach Loop
foreach Loop with List of Objects
This snippet shows how to use a `foreach` loop to iterate over a list of custom objects and access their properties.
Code Snippet
This code defines a `Person` class with `Name` and `Age` properties. A `List
using System;
using System.Collections.Generic;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class ForeachObjectExample
{
public static void Main(string[] args)
{
List<Person> people = new List<Person>()
{
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 25 },
new Person { Name = "Charlie", Age = 35 }
};
Console.WriteLine("Iterating through the list of people:");
foreach (Person person in people)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
}
Concepts Behind the Snippet
This example showcases using `foreach` loop with a collection of objects, demonstrating how to access object properties within the loop. It leverages the power of C# classes and collections to manage data efficiently.
Real-Life Use Case
Imagine a scenario where you need to process a list of products, orders, or employees. You can use a `foreach` loop to iterate through the list and perform actions such as calculating totals, sending notifications, or generating reports for each item.
Best Practices
Interview Tip
Explain the importance of using strongly-typed collections like `List
When to Use Them
Use this approach when you need to iterate over a collection of custom objects and perform operations that involve accessing object-specific properties.
Memory Footprint
The memory footprint is determined by the size of the collection and the size of each object within the collection. Consider using techniques like paging or lazy loading to handle very large datasets.
Alternatives
Pros
Cons
FAQ
-
How can I filter the objects within the `foreach` loop?
You can use an `if` statement within the loop to filter the objects based on specific criteria. Alternatively, you can use LINQ's `Where` method to filter the collection before iterating over it. -
Can I modify the properties of the objects within the `foreach` loop?
Yes, you can modify the properties of the objects within the loop. However, be careful not to modify the structure of the collection itself (e.g., adding or removing elements) as this can lead to unexpected behavior.