I've come across this a few times and I feel like I'm always writing unessasary code. I'm looking for the most efficient way to compare the value of a field in a list with another list.
For example, let's say I have a viewmodel such as the following:
public class UserContractAddDTO
{
public string ContractId { get; set; }
public bool ContractSelected { get; set; }
public string UserName { get; set; }
}
I put the values of the table into this view model, and then pass it back as an IEnumerable:
IEnumerable<UserContractAddDTO> jsonArray
Now that I have this IEnumerable of UserContractAddDTO's, I will need to loop through it to compare the values that exist already in the database.
Let's say ContractSelected has been updated for some of the rows, so it's set to true. Normally I would use a foreach loop, but it would need to know if the row already exists to avoid duplicate rows.
foreach (UserContractAddDTO u in jsonArray)
{
var a = u.ContractId.ToString();
if (u.ContractSelected == true)
{
foreach (UserPlanSponsorContract up in UserContractList)
{
if (up.PlanSponsorContractId.ToString() == a && up.UserId == userId)
{
//update row
var row = _context.UserPlanSponsorContracts.Where(r => r.PlanSponsorContractId.ToString() == u.ContractId && r.UserId == userId).FirstOrDefault();
row.IsVerified = true;
_context.SaveChanges();
}
else
{
//add row
_context.UserPlanSponsorContracts.Add(new UserPlanSponsorContract
{
UserId = userId,
PlanSponsorContractId = Convert.ToInt32(u.ContractId),
IsVerified = true,
ContractAdminEmailSent = false,
AppliedDate = DateTime.Now,
ReverifyReminder = 0
});
_context.SaveChanges();
}
}
}
else
{
foreach (UserPlanSponsorContract up in UserContractList)
{
if (up.PlanSponsorContractId.ToString() == a && up.UserId == userId)
{
//update row
var row = _context.UserPlanSponsorContracts.Where(r => r.PlanSponsorContractId.ToString() == u.ContractId && r.UserId == userId).FirstOrDefault();
row.IsVerified = false;
_context.SaveChanges();
}
}
}
}
This is one approach I've tried, but I'm looking for a more efficient way of doing it. Thoughts?