C# 使用 foreach 访问层次结构的子成员

C# Access child members of hierarchy with foreach

我正在尝试让 Foreach 为下面的 html 剃须刀工作。最后,我希望 ShoppingCart 成为 CartLines 的列表。我想摆脱 [0] 语句,并使其可变。任何解决方案或最佳方法都会有所帮助。也可以随意编辑 class。

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>

因此您将需要一个嵌套的 foreach:

@foreach (var cart in Model)
{    
    @foreach (var line in cart.Items )
    {
        @Html.DisplayFor(modelItem => line.Product) 
    }
}

遍历你的列表元素,而不是你的 class:

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>