How can I randomly pick a string element out of a list or array?

I'm making a typing aid and I have a method that contains lists of noun/adjectives and verbs. I need it to pick one thing out of each list and turn it into a sentence.

Recommended Answers

All 5 Replies

I'm not a C# expert and don't know the exact function / method names, but the basic way to get a random element is to use whatever 'random' function the language provides to generate a number between 0 and 1, then multiply that by the number of elements in your collection (probably the .count property). Round the result to an integer and you will have an index into your collection. You need to round rather than truncate the result, or you will never access the last element.

Hope this helps.

Try something like

Random random = new Random();
int index = random.Next(0, array.Length); // list.Count for List<T>
string value = array[index]; // where array is string[]

I tried that apegram but,

The code when printed only produces "System.Random"...

public static void GenerateSentence()
        {
            List<string> nouns = new List<string> { "He", "She", "Him", "Billy Bob", "Mike", "Noah"};
            List<string> verbs = new List<string> {"runs","eats","doesn't like"};         
      
            Random noun_rand = new Random(); 
            int index = noun_rand.Next(0,6); // list.Count for List<T>
            string value = nouns[index]; // where array is string[]

            Console.WriteLine(noun_rand);
            Console.ReadLine();
        }

Fix is @ ln10:

Console.WriteLine(value);

You are priniting the random variable in your code, not the indexed value of the array

ah, I thought I had to save it in another variable. Didn't think of value.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.