【发布时间】:2018-06-08 02:42:41
【问题描述】:
我正在尝试确定在每个标签上显示随机键的正确语法。
//declare random
Random rnd = new Random();
//create the sorted list and add items
SortedList<string,string> sl = new SortedList<string,string>();
sl.Add("PicknPay", "jam");
sl.Add("Spar", "bread");
sl.Add("Checkers", "rice");
sl.Add("Shoprite", "potato");
sl.Add("Cambridge", "spinash");
int Count = 0;
int nValue = rnd.Next(5);
int newindex = 0;
int seekindex;
for (seekindex = 0; seekindex > nValue; seekindex++)
{
newindex = rnd.Next(seekindex);
}
lbl1.Text = "";
foreach (var item in sl.Keys)
{
lbl1.Text += "," + Convert.ToString(item.IndexOf(item));
}
lbl1.Text = lbl1.Text.TrimStart(',');
【问题讨论】:
-
您是否尝试从您的
SortedList中选择一个唯一的随机键来显示在三个标签中的每一个中?您的代码表明您正在尝试在lbl1.Text中显示所有这些,用逗号分隔。 -
我不确定我是否理解正确。您想在自己的标签中显示
sl中的每个Key吗? -
如果您想随机打乱您的排序列表,您可以在第二次为每个stackoverflow.com/a/4262134/3254405 使用 linq order by
-
表单加载时。这三个标签应该显示一个从排序列表中随机选择的键...例如,当表单加载时,标签 1 将显示“spar”,标签 2 显示“shopright”,label3 显示 cambridge,但如果再次加载表单,则应该选择上面随机的不同键
标签: c# collections labels keyvaluepair