随机生成彩票(c#)

 static int[] red = new int[6] { 0, 0, 0, 0, 0, 0 };//要不能有重复
        static Random r = new Random();
        static string Rand_CaiPiao()
        {
            int blue = r.Next(1, 17);

            for (int i = 0; i < red.Length; i++)
            {
                int num = r.Next(1, 33);

                bool chong = Repetition(num);
                //Console.WriteLine(chong);//true有重复

                if (chong == false)
                {
                    red[i] = num;
                }
                else
                {
                    while (chong)
                    {
                        num = r.Next(1, 33);
                        chong = Repetition(num);
                    }
                    red[i] = num;
                }
            }


            string data = "";
            Array.Sort(red);
            for (int i = 0; i < red.Length; i++)
            {
                data += red[i] + ",";
            }
            data += blue.ToString();
            return data;
        }

        //判断红球是否重复
        static bool Repetition(int num)
        {
            for (int i = 0; i < red.Length; i++)
            {
                if (num == red[i])
                {
                    return true;
                }
            }
            return false;
        }

直接调用这个方法就可以获取一组彩票数据了啦!

List<int> red = new List<int>();
            Random rand = new Random();
            while (red.Count < 6)
            {
                int num = rand.Next(32) + 1;
                if (!red.Contains(num))
                {
                    red.Add(num);
                }
            }

//通过委托,调用接口进行排序
            red.Sort(delegate(int o1, int o2)
            {
                return o1.CompareTo(o2);
            });
            //等价于上面
            //其实他是lambda表达式,方法的精简,LINQ查询中常用
            //red.Sort((int o1, int o2) => o1.CompareTo(o2));
            //等价于
            //red = red.OrderBy(t => t).ToList();
            
            foreach (var item in red)
            {
                Console.WriteLine(item);
            }

这样就更简单了

你可能感兴趣的:(c#基础)