foreach(var submission in model.Submissions) { // Will use Ternary Operation, if Response.Response has a null will call secondary descendant. var responses = submission.Sections.SelectMany(obj => obj.Screens.Screen.Responses.Response == null ? obj.Screens.Screen.Responses.Responses.Response.Select(response => new { response.Label, response.Value, response.Type }) : obj.Screens.Screen.Responses.Response.Select(response => new { response.Label, response.Value, response.Type })).ToList(); var invoices = responses.Where(obj => obj.Label.Contains("Invoice Number(s)")).Select(obj => obj.Value).ToList(); var printed = responses.FirstOrDefault(obj => obj.Label.Contains("Printed Name")).Value; var signature = responses.FirstOrDefault(obj => obj.Label.Contains("Signature")).Value; var photo = responses.FirstOrDefault(obj => obj.Label.Contains("Photo")).Value; var location = responses.FirstOrDefault(obj => obj.Label.Contains("Location")).Value; using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings[@"CommerceDB"].ConnectionString)) { connection.Open(); // Will read the data that resides in the database, to gather Invoice Numbers to ensure a duplicate doesn't exist. foreach (string invoice in invoices) { using (SqlCommand command = new SqlCommand(query, connection)) { command.Parameters.AddWithValue("@Invoice", invoice); using (SqlDataReader reader = command.ExecuteReader()) while (reader.Read()) if (reader[@"InvoiceNumber"] != DBNull.Value) invoiceFound = reader[@"InvoiceNumber"].ToString(); else invoiceFound = String.Empty; } if (string.Equals(invoice, invoiceFound) && collection.Any(i => i.Equals(invoice))) // If a duplicate is found, will skip the entry. continue; else { using (SqlCommand command = new SqlCommand(@"proc_ProofOfDelivery_Insert", connection)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@SubmissionID", Convert.ToInt32(submission.Id)); command.Parameters.AddWithValue("@ResponseID", submission.ResponseID); command.Parameters.AddWithValue("@UserName", submission.UserName); command.Parameters.AddWithValue("@FirstName", submission.FirstName); command.Parameters.AddWithValue("@LastName", submission.LastName); command.Parameters.AddWithValue("@InvoiceNumber", invoice); command.Parameters.AddWithValue("@PrintedName", printed); command.Parameters.AddWithValue("@Signature", signature); command.Parameters.AddWithValue("@Photo", photo); command.Parameters.AddWithValue("@Location", location); command.Parameters.AddWithValue("@XMLFile", SerializeSubmission(submission)); command.ExecuteNonQuery(); collection.Add(invoice); } } } } }