摆脱在C#中的字符串数组的一个随机值最快的方法? [英] Fastest way to get a random value from a string array in C#?

查看:61
本文介绍了摆脱在C#中的字符串数组的一个随机值最快的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是摆脱在C#中的字符串数组在.NET 2.0框架的一个随机值最快的方法?我想他们可能有过这样的:

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

是的,我知道GetRandomValue()是不是一个实际的方法,有没有类似的东西,或多或少同样短暂的甜蜜?

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

推荐答案

不是内置的,但很容易添加...

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)

在C#3.0,这可能是一个扩展方法:

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

这篇关于摆脱在C#中的字符串数组的一个随机值最快的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆