samedi 29 août 2015

C# : 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.




Aucun commentaire:

Enregistrer un commentaire