通用字典参数C#(从中返回随机键) [英] generic dictionary param c# (return random key from it)

查看:79
本文介绍了通用字典参数C#(从中返回随机键)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以具有一个接收通用字典参数并从中返回随机键的函数?由于字典的键"值可以是任何数据类型,因此我希望字典参数是通用的,并且无论数据类型如何,都可以从中返回一个随机键.到目前为止,我已经写了这篇文章,但出现错误.

Is it possible to have a function that receives a generic dictionary param and return a random key from it? Since dictionary "key" values can be any data type, I would like the dictionary param to be generic and return a random key from it no matter what data type. I wrote this so far but am getting an error.

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "1003206");
dict.Add(2, "1234567");
dict.Add(3, "5432567");

int randomKey = (int)RandomDictionaryKeyValue<Dictionary<int, string>>(dict);

private T RandomDictionaryKeyValue<T>(Dictionary<T, T> dict)
    {
    List<T> keyList = new List<T>(dict.Keys);

    Random rand = new Random();
    return keyList[rand.Next(keyList.Count)];
}

我遇到错误:

CS1503参数1:无法从'System.Collections.Generic.Dictionary<int, string>'转换为'System.Collections.Generic.Dictionary<System.Collections.Generic.Dictionary<int, string>, System.Collections.Generic.Dictionary<int, string>>'

我知道如何获取访问列表中的随机项,但是我不知道不知道如何正确地将字典传递给我的方法.

I know how to get Access random item in list, but I don't know how to correctly pass dictionary to my method.

推荐答案

问题是您为字典的键和值指定了相同的泛型类型.

The problem is that you have specified the same generic type for both the key and value of your dictionary.

private TKey RandomDictionaryKeyValue<TKey, TValue>(Dictionary<TKey, TValue> dict)
{
    //snip
}

这篇关于通用字典参数C#(从中返回随机键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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