我想制作一组随机数而不重复。
<Basic>
<Results>
<Result>a1</Result>
<Result>a2</Result>
<Result>a3</Result>
</Results>
</Basic>
正如你在这里看到的,我有list数组有问题id的值,而且我已经创建了另一个数组,从该数组中随机获得4个元素。 但是,我的问题是如何在没有任何重复的Ids的情况下获得这些元素我已经多次尝试过但不幸的是我没有成功。
答案 0 :(得分:3)
最简单的事情是改组你的问题ID,然后选择前四个。
Random rnd = new Random();
randomQuestionId = idS.OrderBy(_ => rnd.Next()).Take(4).ToArray();
答案 1 :(得分:0)
试试这个,这段代码将生成唯一的随机数
int smallestNumber = 1;
int biggestNumber = 50;
//Determine the amount of random numbers
int amountOfRandomNumbers = 10;
//Create a list of numbers from which the routine
//shall choose the result numbers
var possibleNumbers = new List<int>();
for (int i = smallestNumber; i <= biggestNumber; i++)
possibleNumbers.Add(i);
var result = new List<int>();
//Initialize a random number generator
Random rand = new Random();
//For-loop which picks each round a unique random number
for (int i = 0; i < amountOfRandomNumbers; i++)
{
//Generate random number
int randomNumber = rand.Next(1, possibleNumbers.Count) - 1;
result.Add(possibleNumbers[randomNumber]);
//Remove the chosen result number from possible numbers list
possibleNumbers.RemoveAt(randomNumber);
}
//现在循环result
并打印输出
答案 2 :(得分:0)
var pickFour = array
.OrderBy(p => Guid.NewGuid())
.Take(4);