Q:

Linq For Each - Need Advice

I have this block of code. 
var foundAppointments = ServiceLink. FindAppointments(User, SiteSecureKey);    
var MondayAppointments = foundAppointments. SelectMany(x => x.Where(y => y.StartTime. Date. DayOfWeek == DayOfWeek. Monday)).ToList();

Now I have a global list which I add each days appointments too e.g. Monday, Tuesday, Wed etc..
Then I run this:
Appointments. Add(MondayAppointments); ..........

Is there any whay I can run the Monday through Sunday appointments than having to write. 
var TuesdayAppointments = foundAppointments. SelectMany(x=>x. Where(y => y.StartTime. Date. DayOfWeek == DayOfWeek. Tuesday)).ToList();
var WednesdayAppointments = foundAppointments. SelectMany(x=>x. Where(y => y.StartTime. Date. DayOfWeek == DayOfWeek. Wednesday)).ToList();
var ThursdayAppointments = foundAppointments. SelectMany(x=>x. Where(y =>y.StartTime. Date. DayOfWeek == DayOfWeek. Thursday)).ToList();
var FridayAppointments = foundAppointments. SelectMany(x=>x. Where(y => y.StartTime. Date. DayOfWeek == DayOfWeek. Friday)).ToList();
var SaturdayAppointments = foundAppointments. SelectMany(x => x.Where(y => y.StartTime. Date. DayOfWeek == DayOfWeek. Saturday)).ToList();
var SundayAppointments = foundAppointments. SelectMany(x => x.Where(y => y.StartTime. Date. DayOfWeek == DayOfWeek. Saturday)).ToList();
Appointments. Add(TuesdayAppointments);
Appointments. Add(WednesdayAppointments);
Appointments. Add(ThursdayAppointments);
Appointments. Add(FridayAppointments);
Appointments. Add(SaturdayAppointments);
Appointments. Add(SundayAppointments);

Any ideas? 

A:

You can enumerate over values from DayOfWeek enum and get appointments of each day:
var days = Enum. GetValues(typeof(DayOfWeek));
foreach (DayOfWeek dayOfWeek in days)
{
    var dayAppointments = foundAppointments. SelectMany(x => x.Where(y => y.StartTime. Date. DayOfWeek == dayOfWeek)).ToList();
    Appointments. Add(dayAppointments);
}

If you need Monday to be first, then sort days:
var days = Enum. GetValues(typeof(DayOfWeek)).Cast<DayOfWeek>()
               .OrderBy(d => d == DayOfWeek. Sunday)
               .ThenBy(d => d);

BTW why you are adding appointments day by day?  Looks like you can add all at once.  If you want to add appointments in order starting from Monday:
var appintmentsToAdd = foundAppointments
     .SelectMany(x => x)
     .OrderBy(a => a.StartTime. Date. DayOfWeek == DayOfWeek. Sunday)
     .ThenBy(a => a.StartTime. Date. DayOfWeek)
     .ToList();

Appointments. Add(appintmentsToAdd);

