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

如何在C#中无重复随机选取并显示列表中的4个元素?

C# 实现无重复随机选取List元素的三种方式

以下针对你的topLevel集合,分别用while循环、for循环、LINQ三种方式实现无重复随机选取4个元素的功能:

1. While循环实现

通过维护结果集合,循环生成随机索引,直到选够4个不重复的元素:

List<string> topLevel = new List<string> { "000", "100", "200", "300", "400", "500", "600", "700", "800", "900" };
Random random = new Random();
List<string> selectedItems = new List<string>();

while (selectedItems.Count < 4)
{
    int randomIndex = random.Next(topLevel.Count);
    string currentItem = topLevel[randomIndex];
    if (!selectedItems.Contains(currentItem))
    {
        selectedItems.Add(currentItem);
    }
}

// 输出选取结果
foreach (var item in selectedItems)
{
    Console.WriteLine(item);
}

2. For循环实现

通过维护可用索引池,每次选取后移除已用索引,避免重复:

List<string> topLevel = new List<string> { "000", "100", "200", "300", "400", "500", "600", "700", "800", "900" };
Random random = new Random();
List<int> availableIndices = Enumerable.Range(0, topLevel.Count).ToList();
List<string> selectedItems = new List<string>();

for (int i = 0; i < 4; i++)
{
    int poolIndex = random.Next(availableIndices.Count);
    int targetIndex = availableIndices[poolIndex];
    selectedItems.Add(topLevel[targetIndex]);
    availableIndices.RemoveAt(poolIndex);
}

// 输出选取结果
foreach (var item in selectedItems)
{
    Console.WriteLine(item);
}

3. LINQ实现

通过随机排序集合后取前4个元素,代码最简洁:

List<string> topLevel = new List<string> { "000", "100", "200", "300", "400", "500", "600", "700", "800", "900" };
Random random = new Random();

List<string> selectedItems = topLevel.OrderBy(_ => random.Next()).Take(4).ToList();

// 输出选取结果
foreach (var item in selectedItems)
{
    Console.WriteLine(item);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 06:05:21