Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to get a random value from a string array in C#?

What's the fastest way to get a random value from a string array in C# on the .net 2.0 framework? I figured they might have had this:

string[] fileLines = File.ReadAllLines(filePath);
fileLines.GetRandomValue();

Yes, I know GetRandomValue() is not an actual method, is there something similar that's more or less equally short and sweet?

like image 281
Mr. Smith Avatar asked Dec 08 '22 06:12

Mr. Smith


2 Answers

Not built in, but easy enough to add...

static readonly Random rand = new Random();
public static T GetRandomValue<T>(T[] values) {
    lock(rand) {
        return values[rand.Next(values.Length)];
    }
}

(the static field helps ensure we don't get repeats if we use it in a tight loop, and the lock keeps it safe from multiple callers)

In C# 3.0, this could be an extension method:

public static T GetRandomValue<T>(this T[] values) {...}

Then you could use it exactly as per your example:

string[] fileLines = File.ReadAllLines(filePath);
string val = fileLines.GetRandomValue();
like image 141
Marc Gravell Avatar answered Dec 29 '22 01:12

Marc Gravell


Indeed.

Random m = new Random();
string line = fileLines[m.Next(0, fileLines.Length);
like image 38
Noon Silk Avatar answered Dec 28 '22 23:12

Noon Silk