Colonel_Custard
Colonel_Custard

Reputation: 1390

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)
                    {



                    }
}

Upvotes: 0

Views: 4326

Answers (4)

Matthew Watson
Matthew Watson

Reputation: 109537

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.)

Upvotes: 2

tariq
tariq

Reputation: 2258

How about pure linq :

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

Upvotes: 2

Gauthier G. Letellier
Gauthier G. Letellier

Reputation: 3385

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.

Upvotes: 1

BLoB
BLoB

Reputation: 9725

Surely what you want is:

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

Upvotes: 1

Related Questions