获取Dictionary中不重复的随机数(返回Dictionary):
public static Dictionary<TKey, TValue> RandomValues<TKey, TValue>(Dictionary<TKey, TValue> allDic, int randomCount)
{
System.Random rand = new System.Random();
Dictionary<TKey, TValue> newDic = new Dictionary<TKey, TValue>();
int size = allDic.Count;
randomCount = randomCount > size ? size : randomCount;
List<TKey> values = Enumerable.ToList(allDic.Keys);
while (newDic.Count < randomCount)
{
TKey tk = values[rand.Next(size)];
if (!newDic.Keys.Contains(tk))
{
newDic[tk] = allDic[tk];
}
}
return newDic;
}
获取List中不重复的随机数(返回List):
public static List<TKey> RandomValues<TKey>(List<TKey> allList, int randomCount)
{
System.Random rand = new System.Random();
List<TKey> newList = new List<TKey>();
int size = allList.Count;
randomCount = randomCount > size ? size : randomCount;
//List<TKey> values = Enumerable.ToList(allList.Keys);
while (newList.Count < randomCount)
{
TKey tk = allList[rand.Next(size)];
if (!newList.Contains(tk))
{
newList.Add(tk);
}
}
return newList;
}