C# 基于另一个集合(子集合)筛选linq集合(父集合)
我正在基于子集合筛选集合 我的模型如下: 首先C# 基于另一个集合(子集合)筛选linq集合(父集合),c#,asp.net-mvc,linq,C#,Asp.net Mvc,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 { g
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; }
}
以及一个ViewModel,用于将其传递给我的视图
public class ProductsVM
{
public IList<Item> items { get; set; }
public IList<Category> categories { get; set; }
}
现在,我只需要选定类别的项目
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 items=db.items.ToList();
列表过滤器=items.RemoveAll(x=>productsVm.categories.Contains(x.Category.Id));
仅使用类别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));
你试过items.Where(i=>i.Category.isSelected)吗?这是另一个问题,我的视图没有返回我的视图模型,它只返回productsVM中的类别。非常感谢@octavioccl。终于成功了。再次感谢。:)
List<Item> items = db.Items.ToList();
List<Item> filter = items.RemoveAll(x => productsVm.categories.Contains(x.Category.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));