You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Blazor的foreach循环中随机选取2个C#对象展示?

解决方案

要实现从4个RandomPick对象中随机选取2个渲染,你可以通过随机排序后取前2个元素的方式实现,以下是修改后的完整代码:

@foreach (var item in randomSelectedItems)
{                   
    <a class="mylink" href="#" target="_blank">@item.text</a>                   
}

@code { 
    private IEnumerable<RandomPick> allItems = new[] {
        new RandomPick { id = 1, text = "Diamond Price" },
        new RandomPick { id = 2, text = "Gold Price" },
        new RandomPick { id = 3, text = "Web Hosting"},
        new RandomPick { id = 4, text = "Insurance Price"}
    };
    
    private IEnumerable<RandomPick> randomSelectedItems;

    protected override void OnInitialized()
    {
        // 使用Random.Shared生成随机序列,排序后取前2个元素
        randomSelectedItems = allItems
            .OrderBy(_ => Random.Shared.Next())
            .Take(2)
            .ToList();
    }

    public class RandomPick
    {
        public int id { get; set; }
        public string text { get; set; }
    }
}

关键说明:

  • 把原始数据单独存为allItems,避免每次操作修改原数组
  • 在OnInitialized生命周期方法中处理随机筛选逻辑,确保组件初始化时完成随机选择
  • 使用Random.Shared.Next()作为排序依据,实现数组的随机打乱,再通过Take(2)获取前2个元素
  • 如果需要每次组件刷新都重新随机选2个,可以把筛选逻辑放到OnParametersSet或者添加触发刷新的方法

内容的提问来源于stack exchange,提问作者Arjun Ghimire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 13:48:22