C#获取Dictionary中不重复的随机Dictionary

/// <summary>
/// 获取Dictionary中不重复的随机Dictionary
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="dict">原dictionary</param>
/// <param name="count">返回随机个数(如果dict总个数少于count 则返回dict总个数)</param>
/// <returns></returns>
public static Dictionary<TKey, TValue> RandomValues<TKey, TValue>(Dictionary<TKey, TValue> dict, int count)
{//转载请保留http://www.luofenming.com/show.aspx?id=ART2019122800001
    Random rand = new Random();
    Dictionary<TKey, TValue> dic = new Dictionary<TKey, TValue>();
    int size = dict.Count;
    count = count > size ? size : count;
    List<TKey> values = Enumerable.ToList(dict.Keys);
    while (dic.Count < count)
    {
        TKey tk = values[rand.Next(size)];
        if (!dic.Keys.Contains(tk))
        {
            dic[tk] = dict[tk];
        }
    }
    return dic;
}
方法调用
static void Main(string[] args)
{
    Dictionary<string, object> dict = new Dictionary<string, object>();
    dict["t1"] = "www.luofenming.com";
    dict["t2"] = "lqwvje";
    dict["t3"] = 132;
    dict["t4"] = 12111;
    dict["t5"] = 112;

    Dictionary<string, object> dict2= RandomValues(dict,3);
    foreach (KeyValuePair<string, object> kv in dict2)
    {
        Console.WriteLine(kv.Value);
    }
    Console.ReadKey();
}

评论