Array / List / Dictionary之相互转换

 private string[] testAarray = new string[] { "array_01", "array_02", "array_03", "array_04", "array_05" };
    private List<string> testList = new List<string>() { "list_01", "list_02", "list_03", "list_04", "list_05" };
    private Dictionary<int, string> testDic = new Dictionary<int, string>() { { 1, "dictionary_01" }, { 2, "dictionary_02" }, { 3, "dictionary_03" } };

    void Start () {
//Array数组的 复制、转List、转Dictionary
        //Array复制
        string[] copyArray = new string[testAarray.Length];
        //目标数组.CopyTo(接收数组, 复制起点)
        testAarray.CopyTo(copyArray, 0);
        Debug.Log(copyArray.Length);

        //Array转List
        List<string> arrayToList = new List<string>(testAarray);
        Debug.Log(arrayToList.Count);

        //Array转Dictionary
        //命名空间using System.Linq;
        //Array下标作为Dictionary的key,元素作为value,利用lambda转换
        Dictionary<int, string> arrayToDic = testAarray.ToDictionary(arrayItem => System.Array.IndexOf(testAarray, arrayItem), arrayItem => arrayItem);
        Debug.Log(arrayToDic.Count);

//List列表的 复制、转Array、转Dictionary
        //List复制
        List<string> copyList = new List<string>(testList);
        Debug.Log(copyList.Count);

        //List转Array
        string[] listToArray = testList.ToArray();
        Debug.Log(listToArray.Length);

        //List转Dictionary
        Dictionary<int, string> listToDic = testList.ToDictionary(listItem => testList.IndexOf(listItem), listItem => listItem);
        Debug.Log(listToDic.Count);
       
 //Dictionary复制
        Dictionary<int, string> copyDic = new Dictionary<int, string>(testDic);
        Debug.Log(copyDic.Count);

        //Dictionary字典的 复制、转Array、转List
        //Dictionary转Array
        int[] dictionaryKeyToArray = testDic.Keys.ToArray<int>();
        string[] dictionaryToArray = testDic.Values.ToArray<string>();
        Debug.Log(dictionaryKeyToArray.Length);
        Debug.Log(dictionaryToArray.Length);

        //Dictionary转List
        List<int> dictionaryKeyToList = testDic.Keys.ToList<int>();
        List<string> dictionaryToList = testDic.Values.ToList<string>();
        Debug.Log(dictionaryKeyToList.Count);
        Debug.Log(dictionaryToList.Count);
    }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值