我如何(仅)显示排序列表中的键?

how do i display a key (only)from a sorted list?

我正在尝试确定在每个标签上显示随机键的正确语法。

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

实现此目的的一种方法是通过调用 System.Linq 扩展方法 OrderBy and passing it the value returned from 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];