Alp
Alp

Reputation: 1893

unity3d invalid cast exception for Dictionary

I am trying to implement random entry from dictionary function regarded here into unity3d in visual studio : Random entry from dictionary .

private void somefunction() {

            Dictionary<string, Sprite> dict = (Dictionary<string, Sprite>) RandomValues(slotImages).Take(5);

            foreach (KeyValuePair<string, Sprite> keyValue in dict)
            {
                Debug.Log("random slotImages name : " + keyValue.Key); 
            }

}
public IEnumerable<TValue> RandomValues<TKey, TValue>(IDictionary<TKey, TValue> dict)
    {
        System.Random rand = new System.Random();
        List<TValue> values =  Enumerable.ToList(dict.Values);
        int size = dict.Count;
        while (true)
        {
            yield return values[rand.Next(size)];
        }
    }

But I am having following error ;

InvalidCastException: cannot cast from source type to destination type.

Upvotes: 1

Views: 202

Answers (1)

Frauke
Frauke

Reputation: 1582

The code you currently have in RandomValues returns a list of random values from the dictionary, not actual dictionary entries, i.e. key/value pairs. Essentially you're trying to cast an IEnumerable to a Dictionary, which can't be done implicitly.

The following code should do what you want:

public IDictionary<TKey, TValue> RandomValues<TKey, TValue>(IDictionary<TKey, TValue> dict, int count)
{
    if (count > dict.Count || count < 1) throw new ArgumentException("Invalid value for count: " + count);

    Random rand = new Random();

    Dictionary<TKey, TValue> randDict = new Dictionary<TKey, TValue>();
    do
    {
        int index = rand.Next(0, dict.Count);
        if (!randDict.ContainsKey(dict.ElementAt(index).Key))
            randDict.Add(dict.ElementAt(index).Key, dict.ElementAt(index).Value);
    } while (randDict.Count < count);

    return randDict;
}

Please note that you now need to pass in the number of entries you want as an argument. The return value will be a dictionary with count random, unique entries from the original.

Upvotes: 3

Related Questions