5

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?

2

6 Answers 6

12

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();
Sign up to request clarification or add additional context in comments.

5 Comments

Another way to do it is to make rand [ThreadStatic] and use a seed that is derived from system time and ThreadID, and avoid locking altogether ...
Personally, I think it's a bit of an abuse of extension methods to add this as one. It's clearly not required for all string[] arrays within the application.
I only said "could", to illustrate the usage from the OPs question, and extension methods have no cumulative cost on code performance. The container class could be in a "Utils.Arrays" namespace, for example, tightly limiting scope.
I know; but I just think it's a classic example of why extension methods are bad : it's too easy to add useless ones to solve specific problems, rather than adding new general functionality for the benefit or your entire app.
This was pretty helpful for an application I wrote that needed to select random elements from all sorts of different Lists and arrays; so not useless in that context.
1

Indeed.

Random m = new Random();
string line = fileLines[m.Next(0, fileLines.Length);

Comments

1

I don't think arrays support such a function. The easiest way is just to get a random number, and get the corresponding item.

Random rnd = new Random();
String item = fileLines[rnd.next(fileLines.Length);

Comments

1

Try:

fileLines [new Random ().Next (fileLines.Length)]

1 Comment

Calling this multiple times in quick succession (for example, in a tight loop) will return the same line every time.
0

Linq To Sql way

var rFile = fileLines.OrderBy(x => Guid.NewGuid()).FirstOrDefault();

If you see error you should add System.Linq;

Comments

0

I'd have used this method to get random item from an array :

string[] str = {"red","blue","pink","yellow","green","brown"};
int i = new Random.Next(0, str.length);
MessageBox.Show(str[i]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.