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

ぃ、小莉子 提交于 2019-12-06 06:20:34

问题


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?


回答1:


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();



回答2:


Indeed.

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



回答3:


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);



回答4:


Try:

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



回答5:


Linq To Sql way

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

If you see error you should add System.Linq;




回答6:


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]);


来源:https://stackoverflow.com/questions/1392819/fastest-way-to-get-a-random-value-from-a-string-array-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!