【问题标题】:C# random value from dictionary and tuple来自字典和元组的 C# 随机值
【发布时间】:2014-07-28 21:37:51
【问题描述】:

我有以下代码,需要从字典中获取一个包含字符串“Region_1”的随机项。

public static Dictionary<int, Tuple<string, int, CurrencyType>> ItemArray = new Dictionary<int, Tuple<string, int, CurrencyType>>()
{
     { 0xB3E, new Tuple<string, int, CurrencyType>("Region_1", 1500, CurrencyType.Fame) }
};

public static int GenerateItemID(string ShopID)
{
     var GeneratedItem = ItemArray.ElementAt(new Random().Next(0, ItemArray.Count)).Key;

}

如何选择?

【问题讨论】:

    标签: c# random dictionary tuples


    【解决方案1】:

    这一切都不太可能有效...

    首先在类级别创建一个静态Random...如果您在短时间内频繁运行查询,这将阻止non-random behaviour...(它来自一个离散时钟)

    static Random rnd = new Random();
    

    然后:

    var item = ItemArray.Values
       .Where(t => t.Item1 == ShopID)
       .OrderBy(_ => rnd.Next())
       .FirstOrDefault()
    

    【讨论】:

    • +1。请注意,由于需要搜索所有项目,该方法的性能为 O(n) - 无序字典在这里没有帮助。
    猜你喜欢
    • 2023-02-24
    • 2015-09-08
    • 1970-01-01
    • 2010-10-28
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    相关资源
    最近更新 更多