Pick random word from list?

前端 未结 3 2021
春和景丽
春和景丽 2021-01-28 22:21

I´m having trouble picking a random word from a list in another file. Actually I can´t even get it to choose any word. I´m not sure how to connect the 2 files so to say. Hoping

3条回答
  •  隐瞒了意图╮
    2021-01-28 23:07

    Here is the very simple solution:

    Populate your list just one time, or when ever you add any word, call this method. Code:

    private void PopulateTheWordList()
            {
                Console.Write("\n\tAdd a word\n\n");
                WordList.Add(Console.ReadLine());
            }
    

    Now just call this method to get random words:

    private string PickWord()
            {
                Random ran = new Random();
                return WordList[ran.Next(0, WordList.Count)];
            }
    

    If you need to create List of words in another class, then use keyword static:

    static List WordList = new List();
    

    Now you can call it by just writing the class name, like YourClassName.WordList

提交回复
热议问题