C# unity3d字典的强制转换异常无效

C# unity3d字典的强制转换异常无效,c#,dictionary,unity3d,C#,Dictionary,Unity3d,我正试图在visual studio中将字典函数中的随机条目实现为unity3d: 当前在RandomValues中的代码返回字典中的随机值列表,而不是实际的字典条目,即键/值对。实际上,您正试图将一个IEnumerable转换为一个字典,这是无法隐式完成的 以下代码应该执行您想要的操作: public IDictionary<TKey, TValue> RandomValues<TKey, TValue>(IDictionary<TKey, TValue>

我正试图在visual studio中将字典函数中的随机条目实现为unity3d:


当前在
RandomValues
中的代码返回字典中的随机值列表,而不是实际的字典条目,即键/值对。实际上,您正试图将一个
IEnumerable
转换为一个
字典
,这是无法隐式完成的

以下代码应该执行您想要的操作:

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;
}
公共IDictionary随机值(IDictionary dict,int count)
{
如果(count>dict.count | | count<1)抛出新的ArgumentException(“count的无效值:+count”);
Random rand=新的Random();
字典randDict=新字典();
做
{
int index=rand.Next(0,dict.Count);
if(!randDict.ContainsKey(dict.ElementAt(index.Key))
添加(dict.ElementAt(index).Key,dict.ElementAt(index).Value);
}而(randDict.Count

请注意,您现在需要传入您想要作为参数的条目数。返回值将是一个包含原始项的
count
随机唯一项的字典。

RandomValues
返回一个
IEnumerable
,您正试图将其转换到
字典中。没有简单的强制转换-您希望字典包含什么?@Fraukennonnemacher我希望字典包含图像和图像的名称(dictionary dict),例如:“apple”和apple.pngSo图像的名称应该来自哪里?这是slotImages的钥匙吗?在这种情况下,从传递到
RandomValues
的字典中选择一些随机条目,而不是尝试将其转换为
IEnumerable
然后再转换回来,不是更容易吗?@Fraukennonnemacher,图像和名称来自不同的资源。是的,这是钥匙。我正试图以最好的方式从字典中随机选取一些条目。我是否正确地假设您生成的集合不应多次包含同一个精灵?一本字典不能包含同一个键两次,但它看起来像是在做某种老虎机,在这种情况下,您可能需要重复的键。。。
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)];
        }
    }

InvalidCastException: cannot cast from source type to destination type.
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;
}