/// <summary> /// Generates the actual random assignments from the composition of members and gifts. /// </summary> /// <param name="assignGifts"> /// Whether to include gifts in the the random assignment /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> public static string GenerateAssignments(bool assignGifts) { var rand = new Random(); List <Member> members = new MemberDataOperations().GetAll().ToList(); if (members.Count <= 1) { return("There needs to be more than 1 member added to assign"); } List <Gift> gifts = new GiftDataOperations().GetAll().ToList(); if (assignGifts && gifts.Count < 1) { return("There are no gifts to assign"); } var assignments = new Collection <Assignments>(); while (members.Count > 0) { var assignment1 = new Assignments(); var assignment2 = new Assignments(); Assignments assignment3 = null; int index = rand.Next(members.Count); Member member1 = members[index]; members.RemoveAt(index); index = rand.Next(members.Count); Member member2 = members[index]; members.RemoveAt(index); assignment1.MemberId = member1.MemberId; assignment1.AssignedMemberId = member2.MemberId; assignment2.MemberId = member2.MemberId; assignment2.AssignedMemberId = member1.MemberId; Member member3 = null; // Handle the edge case where we have 3 members if (members.Count == 1) { index = rand.Next(members.Count); member3 = members[index]; members.RemoveAt(index); assignment3 = new Assignments(); assignment3.MemberId = member3.MemberId; } if (assignGifts) { Gift gift1 = gifts[rand.Next(gifts.Count)]; Gift gift2 = gifts[rand.Next(gifts.Count)]; assignment1.AssignedGiftId = gift1.GiftId; assignment2.AssignedGiftId = gift2.GiftId; if (member3 != null) { Gift gift3 = gifts[rand.Next(gifts.Count)]; assignment3.AssignedGiftId = gift3.GiftId; assignment2.AssignedMemberId = member3.MemberId; assignment3.AssignedMemberId = member1.MemberId; assignments.Add(assignment3); } assignments.Add(assignment1); assignments.Add(assignment2); } else { if (member3 != null) { assignment2.AssignedMemberId = member3.MemberId; assignment3.AssignedMemberId = member1.MemberId; assignments.Add(assignment3); } assignments.Add(assignment1); assignments.Add(assignment2); } } // We can drop here because we're just going to regenerate from existing data new AssignmentDataOperations().DropAssignmentTable(); if (new AssignmentDataOperations().AddMultipleRecords(assignments) < 2) { return("Assignment failed!"); } return(null); }