我正在制作一个基本的交易或不交易游戏,为此我必须从一个数组中随机挑选 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/