简化具有一个lambda表达式的if语句的嵌套foreach循环

时间:2017-03-17 16:34:51

标签: c# asp.net-mvc lambda

正如标题所指定的那样,我有一个旅行列表,一个旅行有一个票证列表,每张票都连接到一个客户。

我想将每个票务客户ID与我的可变客户ID进行比较,以便仅获取该客户的门票,并且我还希望获得该客户有门票的旅行列表。

   Customer customer = db.Customers.FirstOrDefault(u => u.UserId.Equals(user.Id));
   List<Ticket> Tickets = new List<Ticket>();
   List<Trip> Trips = new List<Trip>();

    foreach (Trip trip in db.Trips)
    {
        trip.Tickets.ForEach(ticket =>
            {
                if (ticket.Customer.UserId == customer.UserId)
                {
                    Tickets.Add(ticket); //Add the trip to Trips
                }
            }
        );
    }

我想到的代码但无法使其正常工作

    Trips = db.Trips.Select(trip => trip.Tickets.FirstOrDefault(ticket =>
        {
            if (ticket.Customer.UserId == customer.UserId)
            {
                Tickets.Add(ticket);
            }
        })).ToList();

3 个答案:

答案 0 :(得分:2)

下面的内容应该可行 - 虽然未经测试但应该让你接近。

List<Trip> trips = db.Trips.ToList();
List<Ticket> tickets = new List<Ticket>()
trips.ForEach(p => tickets.AddRange(p.Tickets.Where(q => q.Customer.UserId == customer.UserId)));

编辑 - 如果您正在尝试获取客户的旅行列表,然后我会以略有不同的方式获取门票列表:

//get a list of customer trips
List<Trip> trips = db.Tickets.Where(p => p.Customer.UserId == customer.UserId).Select(q => q.Trip).ToList();
List<Ticket> tickets = trips.select(p => p.Tickets.Where(q => q.Customer.UserId == customer.UserId).ToList()).ToList();
//or if you're not bothered about hitting the db again:
//List<Ticket> tickets = db.Tickets.Where(p => p.Customer.UserId == customer.UserId).ToList();

答案 1 :(得分:1)

var tickets = db.Trips
    .SelectMany(trip => trip.Tickets)
    .Where(ticket => ticket.Customer.UserId == customer.UserId)
    .ToList();

喜欢那个?

答案 2 :(得分:1)

要获得客户所拥有的仅票证

List<Ticket> tickets = db.Tickets
                       .Where(t => t.Customer.UserId == customer.UserId)
                       .ToList();

要获得所有旅行,其中至少有一张机票供您的客户使用:

List<Trip> trips= db.Trips
                  .Where(t => t.Tickets.Any(ti => ti.Customer.UserId == customer.UserId))
                  .ToList();

然而,这不会加载门票。如果您还希望使用故障单加载行程,只需添加Include(),如下所示:

List<Trip> trips= db.Trips.Include("Tickets")
                  .Where(t => t.Tickets.Any(ti => ti.Customer.UserId == customer.UserId))
                  .ToList();
  

无需查询客户