简体   繁体   中英

How to use a foreach loop with LINQ?

I'm having a few problems using a foreach loop with LINQ, this is the code I have so far what I'm trying to do is get a list of customers associated with a particular booking, any help would be appreciated =]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;   


namespace BookingCustomers
{
    public partial class BookingGuests : System.Web.UI.Page
    {
        private HotelConferenceEntities datacontext = new HotelConferenceEntities();



        private void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                try
                {

                    int id = int.Parse(BookID.Text.ToString());
                    tblBooking booking = datacontext.tblBookings.SingleOrDefault(x => x.BookingID == id);

                    tblVenue venue = datacontext.tblVenues.SingleOrDefault(x => x.VenueID == booking.Venue);


                    List<tblCustomer> customers = new List<tblCustomer>();
                    List<tblBookingGuest> guests = booking.tblBookingGuests.ToList();



                    foreach (list<tblBookingGuest> in tblBookingGuest)
                    {



                    }
}

You are missing the loop variable declaration, and the declared type was wrong - oh, and you were using the wrong sequence. I think this is what you want:

foreach (var guest in booking.tblBookingGuests)
{
    // Do something with guest
}

Note that your line of code

List<tblBookingGuest> guests = booking.tblBookingGuests.ToList();

is superfluous. It will make a copy of the entire sequence of booking guests.

You should just use booking.tblBookingGuests directly in the foreach unless you are going to modify the list itself rather than the items in it. (If you do that, it won't change the original, of course.)

Surely what you want is:

foreach (tblBookingGuest guest in guests)
{
  ...
}

I guess you want to access to all the tblBookingGuest in the booking variable.

foreach (tblBookingGuest guest in guests)
{
 //something
}

Please remember that you cannot directly modify a member of the guests list into the foreach loop.

Hope it could help.

How about pure linq :

    booking.tblBookingGuests.ToList().ForEach(a =>
    {
        // Do your stuff
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM