A problem with a newbie in performance with foreach ... need a consultation

This section is simply read from an Excel spreadsheet. This part works great without performance issues.

IEnumerable<ImportViewModel> so=data.Select(row=>new ImportViewModel{
                  PersonId=(row.Field<string>("person_id")),
                  ValidationResult = ""
                  }).ToList();

Before moving on to the view, I want to set ValidationResult, so I have this piece of code. If I comment on this, the model will be quickly passed to the view. When I use foreach, it will take a minute. If I have a hardcode value for item.PersonId, then it works fast. I know that I am doing something wrong, I just don’t know where to start, and what works best for me.

foreach (var item in so)
                {
                    if (db.Entity.Any(w => w.ID == item.PersonId))
                    {
                        item.ValidationResult = "Successful";
                    }
                    else
                    {
                        item.ValidationResult = "Error:  ";
                    }
                 } 

return View(so.ToList());
+3
source share
2 answers

You need to do something like this:

var ids = so.Select(i=>i.PersonId).Distinct().ToList();
// Hitting Database just for this time to get all Users Ids
var usersIds = db.Entity.Where(u=>ids.Contains(u.ID)).Select(u=>u.ID).ToList();
foreach (var item in so)
                {
                    if (usersIds.Contains(item.PersonId))
                    {
                        item.ValidationResult = "Successful";
                    }
                    else
                    {
                        item.ValidationResult = "Error:  ";
                    }
                 } 

return View(so.ToList());
+2
source

. , , . excel, . ( , ). .

+5

All Articles