Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Linq and lambda to flatten a list

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.

like image 308
jim Avatar asked Nov 29 '22 05:11

jim


1 Answers

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);
    
like image 71
Jon Skeet Avatar answered Dec 10 '22 06:12

Jon Skeet