-5

I need to generate a random string from a pool of 6 pre-generated strings. I created a list, but I don't understand how to use "random" to generate one random string out of that list.

This is what I have so far:

string RandomPowerSentence()
{
    Random rnd = new Random();
  
    List<string> powerStrings = new List<string>()
    {
        "You are kind!",
        "You are beautiful!",
        "You are smart!"
    };

    //I assume that here I put the code that generates a random string out of the list with rnd
    

    return  "the random string from the list";

Help will be very appreciated!

I used the random class, but I don't understand/know how to use it with strings and not ints.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • 1
    get a random number in the range of 0 - `powerStrings.Count - 1` then use that number as an index for the `powerStrings` list. – frankM_DN Nov 22 '22 at 19:27
  • 1
    welcome to stackoverflow. seems like a typical [homework question](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) to me. can you please share what you've tried and researched so far? we'll gladly help if you're stuck somewhere, but you should first attempt to solve the task on your own - and be able to describe your efforts. i recommend taking the [Tour], as well as reading [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and [what's on topic](https://stackoverflow.com/help/on-topic). – Franz Gleichmann Nov 22 '22 at 19:49

1 Answers1

0

This is one solution:

string RandomPowerSentence()
{
    Random rnd = new Random();

    int myRandomNumber;

    List<string> powerStrings = new List<string>()
    {
        "You are kind!",
        "You are beautiful!",
        "You are smart!",
        "You are awesome!",
        "You are funny!",
        "You're a f*cking A!"
    };

    // rnd.Next(int, int)   Returns a positive random integer within the specified minimum and maximum range (includes min and excludes max).
    myRandomNumber = rnd.Next(0, powerStrings.Count);

    return powerStrings[myRandomNumber];
}

An explanation of the usage of "Random()": https://www.tutorialsteacher.com/articles/generate-random-numbers-in-csharp

An explanation of the usage of "Count": https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.count?view=net-7.0

RebootDeluxe
  • 762
  • 3
  • 16
  • Mind that you should not create a new `Random` instance on each method call. Use at least a class-scoped one. – Fildor Nov 22 '22 at 20:06