Search code examples
c#collectionslabelkeyvaluepair

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


I'm trying to determine the proper syntax for displaying a random key on each label.

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

Solution

  • One way to do this would be get a randomly ordered list of the keys by calling the System.Linq extension method OrderBy and passing it the value returned from Random.Next(), then take the first three items from this shuffled list:

    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];