Search code examples
c#linqforeachasp.net-mvc-5

How do optimize nested loop and filter from another list using linq c#


I am trying to filter a flattened nested loop and filter from another list. So below is what I have been able to do. I tried this approach but when I run the query it does not save anything in the database. I need help to check and ignore existing records (same MemberId and Description) in the Tasklist table.

var addedtop = from a in db.TaskLists select new {a.MemberId,a.Description};
var membtasks = from m in members
                        from n in tasks
                        select new { m, n };

       
        TaskList taskList = new TaskList();
        foreach (var item in membtasks)
        {
            var exist = db.TaskLists.Where(a => a.Description == item.n && a.MemberId == item.m);
            if(exist == null)
            {    
            taskList .Description = item.n;
            taskList .MemberId = item.m;
            db.taskList .Add(taskList );
            db.SaveChanges();

            }
       }
        return Redirect(url);

Solution

  • The problem is exists will never be null. The line var exist = db.TaskLists.Where(a => a.Description == item.n && a.MemberId == item.m); returns an IQueryable that describes your query but hasn't actually executed against the database yet.

    Try changing the line to:

    var exist = db.TaskLists.Where(a => a.Description == item.n && a.MemberId == item.m).SingleOrDefault();
    

    This executes the query and checks if there is a single item that satisfies your query. If there is no result at all the query returns null which will execute the code inside your if statement.