如何从排序列表中显示一个键(仅限)?

时间:2018-06-07 17:54:18

标签: c# collections labels keyvaluepair

我试图确定在每个标签上显示随机密钥的正确语法。

display random sorted list key on label

//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(',');

1 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是通过调用System.Linq扩展方法OrderBy获取随机排序的密钥列表,并将Random.Next()返回的值传递给它,然后执行第一个这个改组列表中的三个项目:

SortedList<string, string> sl = new SortedList<string, string>
{
    {"PicknPay", "jam"},
    {"Spar", "bread"},
    {"Checkers", "rice"},
    {"Shoprite", "potato"},
    {"Cambridge", "spinash"}
};

var rnd = new Random();
var shuffledKeys = sl.Keys.OrderBy(key => rnd.Next()).ToList();

lbl1.Text = shuffledKeys[0];
lbl2.Text = shuffledKeys[1];
lbl3.Text = shuffledKeys[2];