在c#中怎么随机抽取数组中的数据

2025-02-27 08:11:32
推荐回答(2个)
回答1:

用Random随机生成数组索引,然后返回数组元素

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] a = { 1, 2, 3, 4, 5, 6, 7, 8 };

            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(GetRandomNumber(a));
                // 按任意键,取下一个
                Console.ReadKey();
            }
        }
        
        // 随机抽取数组中的数据
        static int GetRandomNumber(int[] a)
        {
            Random rnd = new Random();
            int index = rnd.Next(a.Length);
            return a[index];
        }
    }
}

回答2:

using System;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] a = { 1, 2, 3, 4, 5, 6, 7, 8 };
 
            for (int i = 0; i < a.Length; i++)
            {
                Console.WriteLine(GetRandomNumber(a));
                // 按任意键,取下一个
                Console.ReadKey();
            }
        }
         
        // 随机抽取数组中的数据
        static int GetRandomNumber(int[] a)
        {
            Random rnd = new Random();
            int index = rnd.Next(a.Length);
            return a[index];
        }
    }
}

用Random随机生成数组索引,然后返回数组元素