Saif Alradhi Saif Alradhi - 3 months ago 10
C# Question

Generate array of random number without duplicates

I want to make an array of random numbers without any duplicate.

private void SetRandomQuestions()
{
var idS = from t in _db.QuestionsTables
where t.Cat_Id == _catId
select new
{ t.Question_Id };

// to get the questions Id from database table
foreach (var variable in idS)
{
array.Add(variable.Question_Id);
}

// generate a random numbers depends on the array list values
var random = new Random();

for (var i = 0; i < _randomQuestionId.Length; i++)
{
_randomNumber = random.Next(array.Count);

for (var j = 0; j < _randomQuestionId.Length; j++)
{
if (_randomQuestionId[j] != array[int.Parse(_randomNumber.ToString())])
{
_randomQuestionId[i] = array[int.Parse(_randomNumber.ToString())];
j = 5;
}
}
}
}


As you see here I have list array has values of questions id and further I have created another array to get 4 elements randomly from that array.
However, my question is how I can get the elements without any duplicate Ids I have tried many times but unfortunately I didn't success with that.

Answer

The simplest thing would be shuffling your question ids and then taking the first four.

Random rnd = new Random();
randomQuestionId = idS.OrderBy(_ => rnd.Next()).Take(4).ToArray();
Comments