views:

93

answers:

2

Hi there

I have a class.

public class MedicalRequest
{
    private int id
    private IList<MedicalDays> Days 
    private string MedicalUser
    ...
}

and another

public class MedicalDays
{
    private int id;
    private DateTime? day
    private MedicalRequest request
    ...
}

I have the MedicalUser so I'm able to select an

IList<MedicalRequest> reqList = dao.FindAll(example);

What I would love to be able to do at this point is flatten out the Lists of MedicalDays and return the DateTime day.

Something like

IList<DateTime> dateList = reqList.SelectMany(i => i.MedicalDays.day);

Can someone give me a push in the right direction?

Thanks for your time.

+12  A: 

You're nearly there:

IEnumerable<DateTime?> dateList = reqList.SelectMany(i => i.MedicalDays)
                                         .Select(m => m.day);

Or:

IEnumerable<DateTime?> dateList = reqList.SelectMany(i => i.MedicalDays,
                                                     (i, m) => m.day);
  • If you need an IList<T> instead of IEnumerable<T> you can call ToList() on the result
  • If you need to work with DateTime instead of DateTime? you can filter out null days like this:

    IEnumerable<DateTime?> dateList = reqList.SelectMany(i => i.MedicalDays)
                                             .Select(m => m.day)
                                             .Where(x => x.HasValue)
                                             .Select(x => x.Value);
    
Jon Skeet
Thank you Jon, very helpful as always.
jim
+3  A: 
IEnumerable<DateTime> dateList = reqList.SelectMany(i => i.MedicalDays)
                                        .Select(i => i.day);
Ben Robinson
Thank you for your response Ben.
jim