2012-08-03 61 views
1

這是this post排除某個模型項目 - MVC/ASP.Net

一個跟進的問題,我有兩個型號:

CarType.cs 

// 
// Holds types of car - this has a one to many relationship with Car class 
// 
[Table("tType")] 
public class CarType 
{ 
    [Key] 
    public int type_id { get; set; } 
    public int dealer_id { get; set; } 
    public string type_name { get; set; } 
    public string type_desc { get; set; } 
    public virtual ICollection<Car> Cars { get; set; } 
} 


Car.cs 

// 
// Holds actual Cars 
// 

[Table("tCar")] 
public class Car 
{ 
    [Key] 
    public int car_id { get; set; } 
    public int dealer_id { get; set; } 
    public int type_id { get; set; } 
    public int car_order { get; set; } 
    public string car_name { get; set; } 
    public virtual ICollection<Rental> Rentals { get; set; } 
    public virtual CarType CarType { get; set; } 
} 

我想有一個視圖模型,在那裏我可以查看汽車類型和多少各車種我有每個車型類別中,所以我創建了一個視圖模型:

public class SearchViewModel 
{ 
    [Required] 
    public DateTime From { get; set; } 
    public int Nights { get; set; } 
    public int dealer_id { get; set; } 
    public IQueryable<CarType> CarTypes { get; set; } 
    // CarTypes as above, has a one to many relationship with the class Car 
} 

鑑於實際汽車(說preBookedCars),我想刪除的predeterminded列表列表o f起的的ViewObject汽車如此,例如,如果CarType(包括一個2很多車)的模型是這樣的:

Mercedes (count = 3) 
....Car 1 
....Car 2 
....Car 3 
Ford (count = 3) 
....Car 4 
....Car 5 
....Car 6 
Citroen (count = 3) 
....Car 7 
....Car 8 
....Car 9 

鑑於汽車列表,我將如何排除汽車的名單從CarType模型 - 例如。

我的列表:租車1,租車4,汽車8,租車9 - 所以我想上面的模型顯示:

Mercedes (count = 2) 
....Car 2 
....Car 3 
Ford (count = 2) 
....Car 5 
....Car 6 
Citroen (count = 1) 
....Car 7 

我知道這是沿(僞LINQ東西線):

var freeCars = (db context).CarTypes 
         .Cars 
         .Except(preBookedCars) 

感謝您的幫助,

馬克

+0

http://msdn.microsoft.com/en-us/library/bb300779.aspx? – 2012-08-03 21:56:54

+0

我相信你需要的代碼可以在這裏找到:http://stackoverflow.com/questions/11092930/check-if-listt-contains-any-of-another-list – bUKaneer 2012-08-03 21:59:12

回答

2

我不知道這是什麼你要找的,但如果你只是想篩選對在CarType對象的收集車,你可以使用這樣的事情:

var preBookedCars = new List<int> { 1, 5, 9 }; 
var myCarType = new CarType(); 
var filteredCars = myCarType.Cars.Where(c => !preBookedCars.Contains(c.car_id)); 

該代碼可適於用在任何你需要的。