如何在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
相关产品推荐
相关产品推荐

