In this post we will see how to flatten collections with nested elements. Let´s imagine that we are developing an application for some kind of learning center: the center offers various class, and every class is imparted by a teacher.

We have the following model:

 public class Teacher : ITeacher
        {
            public Guid Id  { get;set; }
            public string Name  { get;set; }
            public int Phone  { get;set; }
            public List Classes  { get;set; }
        }

 public class Class : IClass
        {
            public Guid Id { get; set; }
            public Guid TeacherId { get; set; }
            public string Description { get; set; }
            public DateTime DayOFWeek { get; set; }
            public DateTime StartTime { get; set; }
            public DateTime EndTime { get; set; }
        }

At some point we are asked to print a report stating in every line the following information:

  • Class description,
  • Day of Week
  • Start time
  • End time
  • Teacher name
  • Teacher Phone

And we are getting as an input parameter a list of teachers:

public IReportData getReportData(List teachers)
{
 //implement code here
}

Now, teachers already contains all that information. But the structure does not match what we are asked, so we need to apply a little transformation to our original input: we need to flatten the data, like this:

var result = teachers.SelectMany(x => x.Classes.
Select(y => new {  description = y.Description, day = y.DayOFWeek, startAt = y.StartTime, endAt = y.EndTime, teacher = x.Name, teacherPhone = x.Phone }));

With the previous code our list is flattened like this:

Class                      Day               start    ends   teacher               teacher´s phone


English B1           Monday        18:00   19:00  John Smith          111-11-22

English B2           Wednesday  18:00   19:00  John Smith          111-11-22

English C2           Friday           19:00   20:00  John Smith          111-11-22

In order to work out that transformation we have used these two linq metods Select and SelectMany:

  • Select: used to project an element of the sequence into a new form.
  • SelectMany: used to project and flatten the sequence