Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a list to view after foreach in c#

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.

like image 819
Ashwin Avatar asked Nov 18 '25 00:11

Ashwin


2 Answers

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;
like image 142
Maysam Razzaghi Avatar answered Nov 20 '25 13:11

Maysam Razzaghi


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.

like image 25
Matt U Avatar answered Nov 20 '25 14:11

Matt U



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!