views:

34

answers:

1
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;
    }
+1  A: 

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