2017-06-17 11 views
0

子コレクションに基づいてコレクションをフィルタリングしています。別のコレクション(子)に基づくlinqコレクション(親)のフィルタリング

次のように私のモデルは以下のとおりです。

まず

public class Item 
    { 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public string Description { get; set; } 
     public double Price { get; set; } 
     public double Stock { get; set; } 
     public Category Category { get; set; } 
     public string ImagePath { get; set; } 
} 

と第二

public class Category 
    { 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public bool isSelected { get; set; } 
    } 

と私の見解に

public class ProductsVM 
{ 
    public IList<Item> items { get; set; } 
    public IList<Category> categories { get; set; } 

} 

と自分の行動を渡すためのViewModel方法ここでカテゴリのリストを表示します(チェックボックスは表示されます)。

次のコードは、選択されていないカテゴリを削除したところで正常に実行されます。

productsVm.categories.RemoveAll(x => x.isSelected == false); 

ここでは、選択したカテゴリのみのアイテムが必要です。

私が試してみました

List<Item> items = db.Items.ToList(); 
    List<Item> filter = items.Where(x => !categories.Any(y=> y.Id == x.Category.Id)).ToList(); 

  List<Item> items = db.Items.ToList(); 
      List<Item> filter = items.RemoveAll(x => productsVm.categories.Contains(x.Category.Id)); 
+0

ハあなたはitems.Where(i => i.Category.isSelected)を試しましたか? –

+0

もう1つの問題は、ViewはViewModelを返さず、productsVMのカテゴリのみを返します。 –

答えて

0

のみを使用してカテゴリのID:

var ids=productsVm.categories.Select(c=>c.Id);//.Distinct(); 
//Using the ids collection now you can filter the item like and IN in sql 
var query=db.Items.Where(i=>ids.Contains(i.Category.Id)); 
+0

ありがとう@octavioccl。最後に働いた。再度、感謝します。 :) –

関連する問題