[英]How to create a list of objects based on a value that the object contains in a list of objects C#
I'm looking for a help. 我正在寻求帮助。 I'm working an exercise based on MVC.
我正在做一个基于MVC的练习。 My model contains 2 classes.
我的模型包含2个类。 The DVD and the Category
DVD和类别
public class DVD
{
public int ID
{ get; set; }
public string Title
{ get; set; }
public decimal Price
{ get; set; }
public int Quantity
{ get; set; }
public int Duration
{ get; set; }
public string Image
{ get; set; }
public virtual IList<Category> Categories_List
{ get; set; }}
Now the Category which is a method contains the following 现在作为方法的类别包含以下内容
public class Category
{
public int Id
{ get; set; }
public string Title
{ get; set; }
public virtual IList<DVD> DVDs
{ get; set; } }
Both DVD and Category are under the Model folder. DVD和类别都在Model文件夹下。 What I want to do is to create a list in my controller of the Category (inside the method of public ActionResult Details(int id = 0) ) to collect all the dvds which are in the category with the id 1 for example.
我想要做的是在我的控制器中创建一个列表(在公共ActionResult Details(int id = 0)的方法内),以收集属于id为1的类别中的所有dvds。
I found something simillar but I have problem when I have to check if the DVD's category id is the same with the one I'm looking for. 我找到了类似的东西,但是当我必须检查DVD的类别ID是否与我正在寻找的那个相同时,我有问题。
Search list of object based on another list of object c# 基于另一个对象列表c#的对象搜索列表
Can anyone help me to do it? 任何人都可以帮我做吗? Thank you
谢谢
Use LINQ Where
. 使用LINQ
Where
。 This will return call of the movies that match a particular category: 这将返回与特定类别匹配的电影的调用:
var moviesMatchingCategory = _masterMovieList.Where(ml => ml.Categories_List.Any(cl => cl.Id == categoryIdToCompare)).ToList();
If you can use linq this will help: 如果你可以使用linq这将有助于:
public IEnumerable<DVD> FindDvdByCategoryId(int categoryId, IEnumerable<DVD> dvdEnumerable)
{
return dvdEnumerable.Where(dvd => dvd.Categories_List.Any(c => c.Id == categoryId)).ToList();
}
List<DVD> list = dvds.Where(x=>x.Categories_List.Contains(y=>y.Id==Id)).ToList();
试试以上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.