Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly pick 4 elements from an array using c#

Tags:

c#

c#-2.0

I am trying to use random function in C# to randomly pick four from an array addetailsID which has over six elements.

I am placing these randomly picked into an another array strAdDetailsID:

 string[] strAdDetailsID = new string[4];
 for (int i = 0; i < 4; i++)
 {
     Random random = new Random();
     int index = random.Next(0, addetailsID.Length);
     value = addetailsID[index].ToString();
     strAdDetailsID[i] = value;
 }

Sometimes, I get two of the same values from the six elements. How can I get all four unique values to be picked?

like image 918
challengeAccepted Avatar asked Jul 01 '26 19:07

challengeAccepted


1 Answers

You might be better off shuffling the array, and then choosing the first 4 elements.

like image 52
FrustratedWithFormsDesigner Avatar answered Jul 03 '26 07:07

FrustratedWithFormsDesigner