C# 从数组/列表中随机获取N个元素

数组和列表方法拓展,复制到一个静态类里即可使用
	
    /// <summary>
    /// 获取数组随机N个元素
    /// </summary>
    /// <param name="array">指定数组</param>
    /// <param name="count">获取元素个数</param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static T[] GetRandomChilds<T>(this T[] array,int count)
    {
        
        T[] tempArray = new T[array.Length];
        T[] tempResultArray = new T[count];
        
        array.CopyTo(tempArray,0);
        
        tempArray.SortRandom<T>();
        
        System.Array.Copy(tempArray,tempResultArray,count);

        return tempResultArray;
    }

    /// <summary>
    /// 获取列表随机N个元素
    /// </summary>
    /// <param name="list"></param>
    /// <param name="count"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static List<T> GetRandomChilds<T>(this List<T> list,int count)
    {
        List<T> tempList = new List<T>();
        
        // tempList = list.GetRange(0,list.Count);
        tempList.AddRange(list);
        tempList.SortRandom<T>();
        return tempList.GetRange(0,count);
    }

	/// <summary>
    /// 数组的2个元素位置调换
    /// </summary>
    public static void Swap<T>(this T[] array, int index1, int index2)
    {
        T temp = array[index2];
        array[index2] = array[index1];
        array[index1] = temp;
    }
    /// <summary>
    /// 列表的2个元素位置调换
    /// </summary>
    public static void Swap<T>(this List<T> list, int index1, int index2)
    {
        T temp = list[index2];
        list[index2] = list[index1];
        list[index1] = temp;
    }

    /// <summary>
    /// 乱序排序数组
    /// </summary>
    public static T[] SortRandom<T>(this T[] array)
    {
        int randomIndex;
        for (int i = array.Length - 1; i > 0; i--)
        {
            randomIndex = UnityEngine.Random.Range(0, i);
            array.Swap(randomIndex, i);
        }
        return array;
    }
    /// <summary>
    /// 乱序排序列表
    /// </summary>
    public static List<T> SortRandom<T>(this List<T> list)
    {
        int randomIndex;
        for (int i = list.Count - 1; i > 0; i--)
        {
            randomIndex = UnityEngine.Random.Range(0, i);
            list.Swap(randomIndex, i);
        }
        return list;
    }
调用如下
		int count = 5;
	    int[] array= new int[] { 0, 1, 2, 3, 4, 5, 6, 7 };
        int[] arrayTemp = array.GetRandomChilds<int>(count);
        // for(int i=0;i<arrayTemp.Length;i++){//Log测试
        //     Debug.Log(arrayTemp[i]);
        // }
        List<string> list = new List<string>(){"a", "b", "c", "d", "e", "f", "g"};
        List<string> listTemp = list.GetRandomChilds<string>(count);
        // for(int i=0;i<listTemp.Count;i++){//Log测试
        //     Debug.Log(listTemp[i]);
        // }
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页