Use linq and lambda to flatten the list

I have a class.

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

and further

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

I have a MedicalUser, so I can choose

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

What I would like to do at this point is to smooth out the lists of medical days and return the DateTime.

Sort of

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

Can someone give me a push in the right direction?

Thank you for your time.

+4
source share
2 answers

You are almost 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 IList<T> instead of IEnumerable<T> , you can call ToList() as a result
  • If you need to work with DateTime instead of DateTime? , you can filter the zero days as follows:

     IEnumerable<DateTime?> dateList = reqList.SelectMany(i => i.MedicalDays) .Select(m => m.day) .Where(x => x.HasValue) .Select(x => x.Value); 
+16
source
 IEnumerable<DateTime> dateList = reqList.SelectMany(i => i.MedicalDays) .Select(i => i.day); 
+5
source

All Articles