2013-11-24 3 views
2

나는 고등학교에서 공부하는 데 도움이되는 플래시 카드 응용 프로그램을 구축 중입니다. 사용자는 용어 및 정의를 사전에 입력합니다. 이제는 용어와 정의를 무작위로 표시하도록 레이블을 설정하는 방법을 알 수 없습니다. 내 메서드 코드는 다음과 같습니다.사전에있는 특정 키/값에 액세스하는 방법 C#

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이 "용어"사전에서 특정 키와 값을 색인화하기를 원합니다. 그런 다음 텍스트 레이블을 선택한 키 값 (문자열)으로 설정하고 definitionLabel 텍스트를 지정된 값 (문자열)으로 설정하십시오. 내가 거의 어떻게 비주얼 C#을

를 사용하는 여기 내 사전 당신은 OrderedDictionary 사용할 수 있습니다

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 = ""; 
} 
+0

실제로 임의의 항목을 선택하는 것은 쉽지만 가장 어려운 것은 ** 성능 **을 얻는 것입니다. –

답변

0

linq을 사용하여 튜플을 검색 할 수 있습니다. 이것은 요소가 사전에 삽입 된 순서 일 필요는 없음을 유의하십시오.

var tuple = terms.ElementAt(randNum); 
TitleLabel = tuple.Key; 
DescriptionLabel = tuple.Value; 
관련 문제