Skip to content

Instantly share code, notes, and snippets.

@JasonOffutt
Created May 14, 2013 16:55
Show Gist options
  • Save JasonOffutt/5577541 to your computer and use it in GitHub Desktop.
Save JasonOffutt/5577541 to your computer and use it in GitHub Desktop.
Example refactoring large nested foreach loops with linq queries.
//
// THIS WORK IS LICENSED UNDER A CREATIVE COMMONS ATTRIBUTION-NONCOMMERCIAL-
// SHAREALIKE 3.0 UNPORTED LICENSE:
// http://creativecommons.org/licenses/by-nc-sa/3.0/
//
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Linq;
using Rock.CheckIn;
using Rock.Model;
namespace Rock.Workflow.Action.CheckIn
{
/// <summary>
/// Loads the schedules available for each group
/// </summary>
[Description("Loads the schedules available for each group")]
[Export(typeof(ActionComponent))]
[ExportMetadata( "ComponentName", "Load Schedules" )]
public class LoadSchedules : CheckInActionComponent
{
/// <summary>
/// Executes the specified workflow.
/// </summary>
/// <param name="action">The workflow action.</param>
/// <param name="entity">The entity.</param>
/// <param name="errorMessages">The error messages.</param>
/// <returns></returns>
/// <exception cref="System.NotImplementedException"></exception>
public override bool Execute( Model.WorkflowAction action, Data.IEntity entity, out List<string> errorMessages )
{
var checkInState = GetCheckInState( action, out errorMessages );
if ( checkInState == null )
{
return false;
}
var groupTypes = ( from f in checkInState.CheckIn.Families
where f.Selected
from p in f.People
where p.Selected
from gt in p.GroupTypes
where gt.Selected
select gt ).ToList();
var kioskGroupTypes = ( from kgt in checkInState.Kiosk.KioskGroupTypes
from gt in groupTypes
where gt.GroupType.Id == kgt.GroupType.Id
select kgt ).ToList();
// Find common groups for the selected location that match the kiosk's location
var groups = ( from gt in groupTypes
from l in gt.Locations
where l.Selected
from kgt in kioskGroupTypes
from lkgt in kgt.KioskLocations
where lkgt.Location.Id == l.Location.Id
from g in l.Groups
where g.Selected
select g ).ToList();
foreach (var group in groups)
{
var kioskGroup = kioskLocation.KioskGroups.FirstOrDefault( g => g.Group.Id == group.Group.Id );
if ( kioskGroup == null )
continue;
foreach ( var kioskSchedule in kioskGroup.KioskSchedules )
{
if ( group.Schedules.Any( s => s.Schedule.Id != kioskSchedule.Schedule.Id ) )
continue;
var checkInSchedule = new CheckInSchedule
{
Schedule = kioskSchedule.Schedule.Clone( false )
};
group.Schedules.Add( checkInSchedule );
}
}
SetCheckInState( action, checkInState );
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment