LoginSignup
10

More than 5 years have passed since last update.

2重foreachをLINQを使って

Posted at

public class Student
{
    public string Name;
}

public class Class
{
    public Student[] Students;
}

public class School
{
    public Class[] Classes;
}

Schoolから全Studentの名前のリストを作りたい場合

foreachなら


var names = new List<string>();
foreach (var @class in school.Classes)
{
    foreach (var student in @class.Students)
    {
        names.Add(student.Name);
    }
}

LINQを使うと


var names = school.Classes
    .SelectMany(o => o.Students)
    .Select(o => o.Name)
    .ToList();

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10