如何访问字典C#中的特定键/值

时间:2013-11-24 05:26:06

标签: c# dictionary

我正在制作闪存卡应用程序,以帮助我在高中学习。用户在字典中输入术语和定义。现在我无法弄清楚如何设置标签随机显示一个术语及其定义。我的方法代码是这样的:

public void startQuiz()
{
   Random random = new Random();
   int randNum;

   //My dictionary with all the terms and 
   //definitions is called terms

   randomNum = random.Next(terms.Count);
   termLabel.Text = // ???
   definitionLabel.text = //???
}

我希望这足够连贯。我基本上希望randomNum从我的“术语”字典中索引特定的键和值。然后将termLabel文本设置为所选键值(这是一个字符串),并将definitionLabel文本设置为指定值(也是一个字符串)。我很乐意提供澄清,因为我几乎不学习如何使用visual c#

这是我的词典

Dictionary<string, string> terms = new Dictionary<string, string>()

//Here is how terms get added
private void addTermButton_Click(object sender, EventArgs e)
{
    term = termBox.Text;
    definition = definitionBox.Text;
    terms.Add(term, definition);
    //Clear text boxes for more terms and definitions
    termBox.Text = "";
    definitionBox.Text = "";
}

2 个答案:

答案 0 :(得分:5)

您可能想要使用OrderedDictionary

http://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx

然后您就可以使用索引了。

答案 1 :(得分:0)

您可以使用linq检索元组。请注意,这不一定是元素插入字典的顺序。

 var tuple = terms.ElementAt(randNum);
 TitleLabel = tuple.Key;
 DescriptionLabel = tuple.Value;