mercredi 31 juillet 2019

How to generate a random list of strings from an array

I want to generate a random list of 5 string values from an array of string.
type options. I have an string[] called 'Items':

private static string[] Items = new[]
{
    "Widgets", "Wotsits", "Grommits"
};

Using the options in this array, I want to instantiate a List<string> collection with 5 random strings. I am trying to do it like this:

    public List<string> List()
    {
        var r = new Random();
        return Enumerable.Range(1, 5).Select(index => new List<string>()
        {
           Items[r.Next(Items.Length)]

        });
    }

I cannot get it to work. One problem I have is I use Enumerable.Range but this creates a type error which I have been unable to solve with .ToList().

Is there a way to do it?




Aucun commentaire:

Enregistrer un commentaire