Home > Mobile >  [Solved]How to return a list to view after foreach in c#
[Solved]How to return a list to view after foreach in c#

Time:10-26

I have this code where I am iterating over objects using foreach loop

 public ActionResult userDocs()
 {
           
    var user = Server.HtmlEncode(Request.Cookies["UserName"].Value);
    var role = db.userdetails.FirstOrDefault(s => s.UserName == user).FullName;
    var test = "kokulchellamuthu1programmer";
            
    var find = db.ApplySchedule.Where(x => x.CC.Contains(test)).ToList();
            
    foreach(var i in find)
    {
        var res = db.docinfo.Where(z => z.RequestID == i.BookingID).ToList();
    }

    return View(res);
}

Now I want to return the res variable to view in order to display matching downloadable documents to the user, I am unable to return it to the view as the code doesn't compile, can someone please help me with this?

Thanks.

CodePudding user response:

You've defined the res variable inside the foreach block so it's inaccessible in your return res; statement. Lift the res out of there, so it'd look like this:

// Replace DocInfo with the correct type name of the db.docinfo model
var res = new List<DocInfo>();

foreach (var i in find)
{
    var entities = db.docinfo.Where(z => z.RequestID == i.BookingID).ToList();
    res.AddRange(entities);
}

return View(res);

However, I think you don't even really need the foreach. You may be able to just do:

var res = db.docinfo.Where(z => find.Any(f => f.BookingID == z.RequestID)).ToList();

If that results in an invalid operation exception or similar then the first part of the answer should still resolve the issue.

CodePudding user response:

You must define an empty list before Foreach and add that item to the defined list for each item found equal to your condition. According to the code below :

 List<string> ids = new List<string>();
 foreach(var i in find)
            {

                var id = db.docinfo.Where(z => z.RequestID == i.BookingID);
                ids.Add(id);
            }
return ids;
  • Related