生成若干随机数,且不重复

 CSDN大神caozhy关于生成1-20随机数,生成10个,不能重复 LINQ写法

var num = Enumerable.Range(1, 20)
    .Select(x => new{ v = x, k = Guid.NewGuid().ToString() }).ToList()
    .OrderBy(x => x.k)
    .Select(x => x.v)
    .Take(10).ToList();
foreach(var i innum)
{
    Console.WriteLine(i);
}

补充:上方法可能会出现重复

            bool[] flag = new bool[initN];
            int[] result = new int[10];
            Random ran = new Random();
            for (int i = 0; i < result.Length; i++)
            {
                int temp = ran.Next(0, flag.Length);
                while (flag[temp])
                {
                    temp = ran.Next(0, flag.Length);
                }
                flag[temp] = true;
                result[i] = temp;
            }
            foreach (int i in result)
            { Console.WriteLine(i); }




?

你可能感兴趣的:(生成若干随机数,且不重复)