C#使用foreach访问层次结构的子成员 [英] C# Access child members of hierarchy with foreach

查看:74
本文介绍了C#使用foreach访问层次结构的子成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使Foreach适用于以下html剃须刀.最终,我希望ShoppingCart成为CartLines的列表.我想摆脱[0]语句,并使其可变.任何解决方案或最佳方法都会有所帮助.也可以随时编辑课程.

I am trying to make Foreach work for the html razor below. At the end of the day, I want ShoppingCart to be a list of CartLines. I want to get rid of the [0] statement, and make it variable. Any solution or optimal method would help. Feel free to edit the class also.

class ShoppingCart
{
    public IList<CartLine> Items { get; } = new List<CartLine>();

    public ShoppingCart() {}
}

public class CartLine
{
    public int CartLineId { get; set; }
    public Product Product { get; set; }
    public int Quantity { get; set; }
}

@model IEnumerable<ShoppingCart>
@foreach (var item in Model)
{
   <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Items[0].Product)
        </td>

推荐答案

遍历列表元素而非类:

class ShoppingCart
{
    public IList<CartLine> Items { get; } = new List<CartLine>();

    public ShoppingCart() {}
}

public class CartLine
{
    public int CartLineId { get; set; }
    public Product Product { get; set; }
    public int Quantity { get; set; }
}

@model ShoppingCart
@foreach (var item in Model.Items)
{
   <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Product)
        </td>

这篇关于C#使用foreach访问层次结构的子成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆