我正在创建一个循环,每次循环时随机选择正确的第9个元素。
我的循环中共有99个元素。
每个第9个元素都是相同的(%9)。我需要在每次打开应用程序时随机循环其中的90个。
检查我的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string[] assignments = new string[] { "https://cdn2.iconfinder.com/data/icons/animals/48/Turtle.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Butterfly.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Dolphin.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Elephant.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Hippopotamus.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Panda.png" };
Random rnd = new Random();
string[] randomingArray = assignments.OrderBy(x => rnd.Next()).ToArray();
string repeatNumber = "";
List<string> animals = new List<string>();
for (int i = 1; i < 100; i++)
{
if (i == 9)
{
repeatNumber = randomingArray[i % randomingArray.Length];
animals.Add(repeatNumber);
}
else if ((i % 9) == 0)
{
animals.Add(repeatNumber);
}
else
{
// random animals.Add(); <-- it should loop randomly here.
}
ItemsControl1.ItemsSource = animals;
}
}
}
之后我将我的元素添加到列表中并通过绑定将该列表发送到xaml。
答案 0 :(得分:1)
我认为这会给你想要的结果:
private Random rnd = new Random();
public MainWindow()
{
InitializeComponent();
string[] assignments = new string[]
{
"https://cdn2.iconfinder.com/data/icons/animals/48/Turtle.png",
"https://cdn2.iconfinder.com/data/icons/animals/48/Butterfly.png",
"https://cdn2.iconfinder.com/data/icons/animals/48/Dolphin.png",
"https://cdn2.iconfinder.com/data/icons/animals/48/Elephant.png",
"https://cdn2.iconfinder.com/data/icons/animals/48/Hippopotamus.png",
"https://cdn2.iconfinder.com/data/icons/animals/48/Panda.png"
}.OrderBy(x => rnd.Next()).ToArray();
string[] animals =
Enumerable
.Range(0, 99)
.Select(i => assignments[i % assignments.Length])
.ToArray();
foreach (int i in Enumerable.Range(1, 9))
{
animals[i * 9] = assignments[9 % assignments.Length];
}
ItemsControl1.ItemsSource = animals;
}
只需一小段提示即可省去麻烦,请始终将Random
变量设为单个字段 - 这样可以避免因快速调用代码重复随机数而导致的潜在错误。在这段代码中不会发生这种情况,但这只是一个很好的习惯。
我刚刚意识到我可以通过这样做失去foreach
循环:
string[] animals =
Enumerable
.Range(0, 99)
.Select(i => assignments[i % 9 == 0 ? 9 : i % assignments.Length])
.ToArray();
那更好。
答案 1 :(得分:0)
var rand = new Random();
int value = rand.Next(0, 99); // 0 is the min and 99 is the max
要获得数组中的随机元素,您只需执行
var result = randomingArray[value];
如果您需要检查数字是否为9,那么
if(value == 9)
{
}
如果你只需要每次都可以选择第9个元素
var result = randomingArray[9];