简体   繁体   English

如何在LINQ中使用foreach循环?

[英]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 =] 我在LINQ上使用foreach循环遇到一些问题,到目前为止,这是我要尝试执行的代码,该操作是获取与特定预订相关的客户列表,任何帮助将不胜感激=]

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. 除非您要修改列表本身而不是其中的项目, 否则应该直接在foreach使用booking.tblBookingGuests (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. 我想您想访问预订变量中的所有tblBookingGuest。

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

Please remember that you cannot directly modify a member of the guests list into the foreach loop. 请记住,您不能直接将来宾列表的成员修改为foreach循环。

Hope it could help. 希望它能有所帮助。

How about pure linq : 纯linq怎么样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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