C#でforeachループを使う方法は?


C#のforeachループは、配列やコレクションなどの反復可能なオブジェクトに対して、各要素を順番に処理するために使用されます。以下は、foreachループを使用する方法の例です。

配列の場合

int[] numbers = { 1, 2, 3, 4, 5 };

foreach (int num in numbers)
{
    Console.WriteLine(num);
}

コレクションの場合

List<string> names = new List<string> { "John", "Mary", "Tom" };

foreach (string name in names)
{
    Console.WriteLine(name);
}

カスタムオブジェクトの場合

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

List<Person> people = new List<Person>
{
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Mary", Age = 25 },
    new Person { Name = "Tom", Age = 40 }
};

foreach (Person person in people)
{
    Console.WriteLine("Name: {0}, Age: {1}", person.Name, person.Age);
}


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.