c# - 从数组 C# 中消除重复项

标签 c# arrays

我正在制作一个基本的交易或不交易游戏,为此我必须从一个数组中随机挑选 10 个决赛入围者,不要重复。

我的结构和数组是这样设置的

public struct People
{
    public string firstname;
    public string lastname;
    public int age;
}

class Program
{
    public static People[] People1 = new People[40];
    public static People[] Finalists1 = new People[10];
    public static People[] Finalist1 = new People[1];

我的入围方法是这样设置的

Random rand = new Random();

for (int i = 0; i < Finalists1.Length; i++)
{
    num = rand.Next(0, People1.Length);           
    Finalists1[i].lastname = People1[num].lastname;
    Finalists1[i].firstname = People1[num].firstname;
    Finalists1[i].age = People1[num].age;
}

如何消除重复的条目,同时保持数组中有 10 个人?

最佳答案

由于初始数组不包含重复项,您可以按随机顺序对其进行排序并选择 10 个顶部项目:

   Finalists1 = People1
     .OrderByDescending(item => 1)   // if people have some points, bonuses etc.
     .ThenBy(item => Guid.NewGuid()) // shuffle among peers
     .Take(10)                       // Take top 10
     .ToArray();                     // materialize as an array

如果进入决赛的人不是完全随机的(例如参赛者可以获得积分、奖金等)更改.OrderByDescending(item => 1),例如

     .OrderByDescending(item => item.Bonuses)

如果你不想使用Linq,你可以直接从urn中绘制People而不返回:

     private static Random random = new Random();  

     ... 

     List<People> urn = new List<People>(People1); 

     for (int i = 0; i < Finalists1.Length; ++i) {
       int index = random.Next(0, urn.Count);

       Finalists1[i] = urn[index];
       urn.RemoveAt(index);
     } 

关于c# - 从数组 C# 中消除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40544408/

相关文章:

C# 0(减号)uint = 无符号结果?

c# - 与数据库绑定(bind)后在下拉列表中添加默认值

arrays - 如何在长度为 n 的单热数组 1 的两侧填充 1

c# - MS 图表控件 : Formatting Axis Labels

c# - 在 Windows XP 上,在单个 c : drive 上以编程方式将页面文件设置为 "No Paging File"

c# - C# 从列表中获取数据

php - 从 mysql 检索一条记录并将其存储在 PHP 的数组中

python - 从数组值动态填充 numpy 矩阵?

c# - 在属性和方法之间共享角色属性的初始化

c - 关于C中字符串和指针的几个问题