C#,Radom.Next()提供了在一定范围生成一个随机数的方法,我现在有个业务场景是给其他部门推送一些数据供他们做抽样检查处理,假设我的数据库里面有N条数据,现在要定期给其随机推送数据,我需要先拿出数据List,然后随机生成若干个数据List索引,最终把这些数据推送给目标数据库。
通过封装,生成定量随机数的方法如下,基本满足所有场景:
/// <summary> /// 根据随机数范围获取一定数量的随机数 /// </summary> /// <param name="minNum">随机数最小值</param> /// <param name="minNum">是否包含最小值</param> /// <param name="maxNum">随机数最大值</param> /// <param name="minNum">是否包含最大值</param> /// <param name="ResultCount">随机结果数量</param> /// <param name="rm">随机数对象</param> /// <param name="isSame">结果是否重复</param> /// <returns></returns> private static List<int> GetRandom(int minNum, bool isIncludeMinNum, int maxNum, bool isIncludeMaxNum, int ResultCount, Random rm, bool isSame) { List<int> randomList = new List<int>(); int nValue = 0; #region 是否包含最大最小值,默认包含最小值,不包含最大值 if (!isIncludeMinNum) { minNum = minNum + 1; } if (isIncludeMaxNum) { maxNum = maxNum + 1; } #endregion if (isSame) { for (int i = 0; randomList.Count < ResultCount; i++) { nValue = rm.Next(minNum, maxNum); randomList.Add(nValue); } } else { for (int i = 0; randomList.Count < ResultCount; i++) { nValue = rm.Next(minNum, maxNum); //重复判断 if (!randomList.Contains(nValue)) { randomList.Add(nValue); } } } return randomList; }