C# 数组乱序,列表乱序

拓展工具类

涉及知识点:
1.泛型的使用
2.拓展方法

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class Tool 
{
    /// <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 void SortRandom<T>(this T[] array){
        int randomIndex;
        for(int i=array.Length-1;i>0;i--){
            randomIndex = Random.Range(0, i);
            array.Swap(randomIndex,i);
        }
    }
    /// <summary>
    /// 乱序排序列表
    /// </summary>
    public static void SortRandom<T>(this List<T> list){
        int randomIndex;
        for(int i=list.Count-1;i>0;i--){
            randomIndex = Random.Range(0, i);
            list.Swap(randomIndex,i);
        }
    }

}

使用案例

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class PanelPinTu : MonoBehaviour
{
    int[] array_pukes = {0,1,2,3,4,5,6,7,8};
    List<string> list_pukes = new List<string>{"a","b","c","d","e","f","g"};
    void Start()
    { 
        //数组
        array_pukes.SortRandom();//排序
        //输出验证
        for(int i=0;i<array_pukes.Length-1;i++){
            Debug.Log(array_pukes[i]);
        }
        
        //列表
        list_pukes.SortRandom();//排序
        //输出验证
        for(int i=0;i<list_pukes.Count-1;i++){
            Debug.Log(list_pukes[i]);
        }
    }
    
    
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值