Blazor:如何自动对 MudBlazor table 中的行进行编号?

Blazor: How to number the rows in MudBlazor table automatically?

我有一个 ASP.NET Blazor 服务器项目,使用 MudBlazor 库来创建 HTML table。我的问题是编号。在下面的示例代码中,行的编号是从 class 属性 中检索的。但是,在我的 class 中,我没有 number 属性 并且在我想要的所有 class 中都有一个数字 属性 并不好在 table 秒后显示。

由于 table 接受项目列表,有没有办法获取正在呈现的项目的索引并使用它而不是 @context.Number 在 MudBlazor table?

<MudTable Items="@Elements.Take(4)" Hover="true" Breakpoint="Breakpoint.Sm" Loading="@_loading" LoadingProgressColor="Color.Info">
    <HeaderContent>
        <MudTh>Nr</MudTh>
        <MudTh>Sign</MudTh>
        <MudTh>Name</MudTh>
        <MudTh>Position</MudTh>
        <MudTh>Molar mass</MudTh>
    </HeaderContent>
    <RowTemplate>
        <MudTd DataLabel="Nr">@context.Number</MudTd>
        <MudTd DataLabel="Sign">@context.Sign</MudTd>
        <MudTd DataLabel="Name">@context.Name</MudTd>
        <MudTd DataLabel="Position" HideSmall="_hidePosition">@context.Position</MudTd>
        <MudTd DataLabel="Molar mass">@context.Molar</MudTd>
    </RowTemplate>
</MudTable>

<MudSwitch @bind-Checked="_hidePosition">Hide <b>position</b> when Breakpoint=Xs</MudSwitch>
<MudSwitch @bind-Checked="_loading">Show Loading</MudSwitch>

此示例代码可以在 MudBlazor Table 中找到。

好吧,有点粗糙但最简单的解决方案是将当前无数字对象映射到包含所需数字的模型。
创建以下内容:

public class Model<T>
{
    public int Number {get; set;}
    public T Value {get; set;}
}

然后按您选择的一些 属性 对您的原始集合进行排序并迭代,每次创建新的 Model 具有原始对象的连续编号和值的对象。
使用这个新模型作为 table 的显示数据源,一切都会很好。

<MudTd DataLabel="Nr">@context.Number</MudTd>
<MudTd DataLabel="Sign">@context.Sign</MudTd>

会变成

<MudTd DataLabel="Nr">@context.Number</MudTd>
<MudTd DataLabel="Sign">@context.Value.Sign</MudTd>
// etc...

同样,它看起来有点粗糙,但可以解决问题。

使用 Linq 的 TakeWhile,您可以对元素进行计数,直到找到与您当前所在行的元素相匹配的元素:

<MudTable Items="@MyElements">
    <HeaderContent>
        <MudTh>Row</MudTh>
    </HeaderContent>
    <RowTemplate>
        <MudTd>@GetRowNumber(context)</MudTd>
    </RowTemplate>
</MudTable>
@code{
    public IEnumerable<object> MyElements => Elements.Take(4);
    public int? GetRowNumber(object element) =>
        MyElements?.TakeWhile(x => x != element).Count();
}