使用 LINQ 查询 MVC 视图中集合内的集合

发布于 2024-09-27 06:31:23 字数 681 浏览 1 评论 0原文

我有一个“产品”和一个“福利”类,如下所示:

现在,我想从我的视图中查询产品集合。我创建了一个获取产品的 LINQ 查询,但我想获取属于该产品的优势集合。

我的视图中的代码(但这只是迭代每个产品,我需要迭代产品中的好处):

<% foreach (var benefit in Model.Products.Where(x => x.ProductId == "123"))
    { %>

类:

public class Product
{
    public string ProductId { get; set; }
    public string ProductName { get; set; }
    public string Description { get; set; }
    public string Features { get; set; }
    public List<Benefit> Benefits { get; set; }
    public decimal Price { get; set; }
}

public class Benefit
{
    public string Name { get; set; }
    public string Value { get; set; }
}

I have a "Product" and a "Benefit" class which is shown below:

Now, I want to query a collection of products from within my view. I've created a LINQ query that gets the products but I want to get at the collection of benefits that belong within the product.

Code within my view (however this just iterates each product and I need to iterate the Benfits within the Product):

<% foreach (var benefit in Model.Products.Where(x => x.ProductId == "123"))
    { %>

Classes:

public class Product
{
    public string ProductId { get; set; }
    public string ProductName { get; set; }
    public string Description { get; set; }
    public string Features { get; set; }
    public List<Benefit> Benefits { get; set; }
    public decimal Price { get; set; }
}

public class Benefit
{
    public string Name { get; set; }
    public string Value { get; set; }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

似狗非友 2024-10-04 06:31:23

Model.Products.Where(x => x.ProductId == "123").SelectMany(p=>p.Benefits)

Model.Products.Where(x => x.ProductId == "123").SelectMany(p=>p.Benefits)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文