开发者

How to return a resource string at random?

ResourceSet rs = Resources.Loading.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true);

so far I have that line, which gets me all the loading messages,

my problem is the ResourceSet is an IEnumerable. I can't figure out what the best way to return a random string in this enumerable would be.

Ideally I'd do something like rs[Utility.Random(rs.Length)]

but I can't figure out how 开发者_高级运维to cast the ResourceSet as a List (for instance), so I don't have to resort to an abomination like a manual loop with something horrible like:

    public static string RandomLoadingMessage()
    {
        ResourceSet rs = Resources.Loading.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true);

        int count = 0;

        foreach(object res in rs)
            count++;

        int position = Utility.Random(count);

        count = 0;

        foreach(DictionaryEntry res in rs)
        {
            if(count++ == position)
                return res.Value.ToString();
        }

        return string.Empty;
    }


Since you mentioned that you have access to LINQ, you can use the Enumerable.Cast<TResult>() extension method to convert the IEnumerable to its generic version (IEnumerable<DictionaryEntry>):

static Random rng = new Random(); // outside of method...

// ...

ResourceSet rs = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true);
var resources = rs.Cast<DictionaryEntry>();
string randomValue = resources.ElementAt(rng.Next(0, resources.Count())).Value.ToString();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜