I am trying to create a random list that will be random each time the user opens the page. The random list will also be larger than the original list (where the objects are coming from) and will contain duplicates.
I cannot seem to find the right way to move an object from list A to list B based on a randomized index to pull from:
Grappling2 = new List<Grappling2>
{
new Grappling2
{
ImageT = "HemaSwordFiore.Images.BGGrapple.IronGate.png",
TrainingText = "Iron Gate"
},
new Grappling2
{
ImageT = "HemaSwordFiore.Images.BGGrapple.IronGate.png",
TrainingText = "Long guard"
}
}
TempListGrappling2 = new List<TempListGrappling2>();//empty list
var rand = new Random();
ndx = rand.Next(3);
for (int counter = 0; counter < 6; counter )
{
ndx ;
TempListGrappling2.Add(new Grappling2[ndx]);
}
}
This obviously gives me an error since I cannot convert Grappling2[] to TempListGrappling2. Any help would be appreciated!
CodePudding user response:
It seems you are asking for something along the lines of this:
// the source list
List<int> first = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// the list to copy into
List<int> second = new List<int>();
var rand = new Random();
// how many items we will insert into the second list
int count = rand.Next(first.Count, int.MaxValue);
for(int i = 0; i < count; i )
{
// a random index from the source list
int index = rand.Next(0, first.Count);
// add that source value to our second list
second.Add(first[index]);
}
Note, the List
is holding int
here, but you may be working with a different data type.
With your code in mind, it could look something like this:
List<Grappling2> Grappling2 = new List<Grappling2>() {
new Grappling2
{
ImageT = "HemaSwordFiore.Images.BGGrapple.IronGate.png",
TrainingText = "Iron Gate"
},
new Grappling2
{
ImageT = "HemaSwordFiore.Images.BGGrapple.IronGate.png",
TrainingText = "Long guard"
}
};
List<Grappling2> TempListGrappling2 = new List<Grappling2>();
var rand = new Random();
int count = rand.Next(Grappling2.Count, int.MaxValue);
for(int i = 0; i < count; i )
{
int index = rand.Next(0, Grappling2.Count);
TempListGrappling2.Add(Grappling2[index]);
}