C# 从列表中删除除其他列表中的值以外的所有内容
我有一个“旅行”列表,其中包含该特定旅行的所有机票列表。我也有实体客户,他们只持有该客户的票证列表 我想要实现的是,让一个拥有所有车票的客户创建一个只包含该客户车票的旅行列表。这将允许我稍后为该用户循环该用户有票的旅行,然后循环该用户的票C# 从列表中删除除其他列表中的值以外的所有内容,c#,asp.net-mvc,C#,Asp.net Mvc,我有一个“旅行”列表,其中包含该特定旅行的所有机票列表。我也有实体客户,他们只持有该客户的票证列表 我想要实现的是,让一个拥有所有车票的客户创建一个只包含该客户车票的旅行列表。这将允许我稍后为该用户循环该用户有票的旅行,然后循环该用户的票 public class Trip { [Key] public int Id { get; set; } public virtual List<Ticket> Tickets { get; set; } } publi
public class Trip
{
[Key]
public int Id { get; set; }
public virtual List<Ticket> Tickets { get; set; }
}
public class Ticket
{
public int Id { get; set; }
public int SeatNumber { get; set; }
public virtual Trip Trip { get; set; }
public virtual Customer Customer { get; set; }
}
public class Customer
{
public int Id { get; set; }
public virtual List<Ticket> Tickets { get; set; }
}
公务舱旅行
{
[关键]
公共int Id{get;set;}
公共虚拟列表票证{get;set;}
}
公务舱票
{
公共int Id{get;set;}
public int SeatNumber{get;set;}
公共虚拟行程{get;set;}
公共虚拟客户客户{get;set;}
}
公共类客户
{
公共int Id{get;set;}
公共虚拟列表票证{get;set;}
}
我的想法是从客户票据列表中检索所有旅行并创建一个唯一旅行列表,然后循环使用票据,然后删除除客户拥有的票据之外的所有票据(我无法真正获得删除部分),我的未完成解决方案:
Customer customer = db.Customers.FirstOrDefault(u => u.UserId.Equals(user.Id));
List<Trip> Trips = customer.Tickets.Select(u => u.Trip).Distinct().ToList();
Trips = Trips.ForEach(t=>t.Tickets.RemoveAll(u=>u.))
Customer-Customer=db.Customers.FirstOrDefault(u=>u.UserId.Equals(user.Id));
List Trips=customer.Tickets.Select(u=>u.Trip.Distinct().ToList();
Trips=Trips.ForEach(t=>t.Tickets.RemoveAll(u=>u.))
更新:
行程表包含所有行程和所有车票
Customer表包含该客户的所有票据
我想创建一个旅行列表,其中只包含指定用户的机票
当我现在检索行程列表时,它将包含所有车票。如果我正确理解您想要一份客户有车票的所有行程的列表,您可以这样做:
Customer.Trips = Trips.Where((trip) => trip.Tickets.Any((ticket) => customer.Tickets.Contains(ticket)));
如果您使用的是实体框架(我假设您基于标记和问题),那么应该禁用延迟加载。这将迫使您在查询数据库时指定要检索的相关实体,这很好,因为您不会因为数据大小而得到意外的点击 一旦这样做了,您就可以像这样检索感兴趣的数据
var customer = db.Customers
.Include(cust => cust.Tickets.Select(ticket => ticket.Trip))
.SingleOrDefault(cust => cust.UserId == user.Id);
Include
和内部Selecet
将确保您检索每张车票上的车票和相关行程,但仅限于与该用户相关的车票
public class Trip
{
[Key]
public int Id { get; set; }
public virtual List<Ticket> Tickets { get; set; }
}
public class Ticket
{
public int Id { get; set; }
public int SeatNumber { get; set; }
public virtual Trip Trip { get; set; }
public virtual Customer Customer { get; set; }
}
public class Customer
{
public int Id { get; set; }
public virtual List<Ticket> Tickets { get; set; }
}
这是一件好事,就好像你在使用惰性加载一样。如果有一个用户非常喜欢巡航,那么他们在旅行中有很多票,这也有很多票。然后,对于每次旅行,您将从数据库中检索大量数据。不过,在数据库的数据量增加之前,您不会意识到存在问题
要禁用延迟加载,请将其添加到DbContext
类型的构造函数体中
this.Configuration.LazyLoadingEnabled = false;
编辑 。。。你能给我一些能用我现在的东西吗 尽管这可以为数据库保存另一组行程,但将
CustomerId
添加到Ticket
实体中
Trips.ForEach(trip => trip.Tickets.RemoveAll(ticket => ticket.CustomerId != user.Id));
不返回任何内容,它只是在ForEach
列表上迭代
返回int并修改实际收集(即不返回新列表)RemoveAll