【问题标题】:generic dictionary param c# (return random key from it)通用字典参数 c#(从中返回随机键)
【发布时间】:2018-04-16 16:47:12
【问题描述】:

是否有可能拥有一个接收通用字典参数并从中返回随机键的函数?由于字典“键”值可以是任何数据类型,我希望字典参数是通用的,并从它返回一个随机键,无论是什么数据类型。到目前为止,我写了这篇文章,但遇到了一个错误。

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&lt;int, string&gt;' 转换为 'System.Collections.Generic.Dictionary&lt;System.Collections.Generic.Dictionary&lt;int, string&gt;, System.Collections.Generic.Dictionary&lt;int, string&gt;&gt;'

我知道如何获取Access random item in list,但我不知道如何正确地将字典传递给我的方法。

【问题讨论】:

    标签: c# dictionary generics


    【解决方案1】:

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

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

    【讨论】:

    • 显然你不能创建Random,如本文所示,但每个人都知道 - 所以请注意示例显示如何将字典作为参数传递而不是 如何从列表中获取随机元素 - stackoverflow.com/questions/767999/…
    • 好地方@AlexeiLevenkov,我已经完全删除了内容。
    【解决方案2】:

    如果您只想从字典中获取随机键,则只需将键类型和值类型传递给您的方法,而不是整个字典类型:

    private TKey RandomDictionaryKeyValue<TKey, TValue>(Dictionary<TKey, TValue> dict)
    {
        List<TKey> keyList = new List<TKey>(dict.Keys);
    
        Random rand = new Random();
        return keyList[rand.Next(keyList.Count)];
    }
    

    并像这样使用它:

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

    【讨论】:

    • 甚至是示例用法,甚至都无法编译。
    【解决方案3】:
    Dictionary<int, string> dict = new Dictionary<int, string>();
    dict.Add(1, "1003206");
    dict.Add(2, "1234567");
    dict.Add(3, "5432567");
    
    int randomKey = (int)RandomDictionaryKeyValue<int, string>(dict);
    

    在我回来检查之前想出了答案。

    private object RandomDictionaryKeyValue<T1, T2>(object dict)
    {
        var dict2 = (Dictionary<T1, T2>)dict;
        List<T1> keyList = new List<T1>(dict2.Keys);                                                                                                                        
    
        Random rand = new Random();
        return keyList[rand.Next(keyList.Count)];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      • 2021-02-12
      相关资源
      最近更新 更多