一个是字典的Linq.Reverse()方法,把所有数反序。好比你是132 反序是231这样子
还有个是Linq的方法.OrderByDescending(o => o.Key).ToDictionary(o => o.Key, p => p.Value);按Key值排序,当我们字典都用的是int的话且按顺序加入,那么这两个方法作用是一样的
测试100万个数的反序
.Reverse
image.png
.OrderByDescending(o => o.Key).ToDictionary(o => o.Key, p => p.Value)
image.png
第二个为什么这么耗时呢 ToDictionary是转化为字典,所以消耗了时间,单独看排序试一试
其实这两个差不多 只是创建字典花费了时间
image.png
测试源码
/**
*Copyright(C) 2019 by #COMPANY#
*All rights reserved.
*FileName: #SCRIPTFULLNAME#
*Author: #AUTHOR#
*Version: #VERSION#
*UnityVersion:#UNITYVERSION#
*Date: #DATE#
*Description:
*History:
*/
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using UnityEngine;
public class TextDic : MonoBehaviour {
Dictionary dic = new Dictionary();
// Use this for initialization
void Start () {
for (int i = 0; i < 1000000; i++)
{
dic.Add(i, i);
}
Stopwatch sw = new Stopwatch();
sw.Start();
//var dicRe= dic.Reverse();
var dicRe = dic.OrderByDescending(o => o.Key);
sw.Stop();
UnityEngine.Debug.Log("sw"+sw.ElapsedMilliseconds);
}
}
/**
*Copyright(C) 2019 by #COMPANY#
*All rights reserved.
*FileName: #SCRIPTFULLNAME#
*Author: #AUTHOR#
*Version: #VERSION#
*UnityVersion:#UNITYVERSION#
*Date: #DATE#
*Description:
*History:
*/
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using UnityEngine;
public class TextDic : MonoBehaviour {
Dictionary dic = new Dictionary() {
{"b",1 },
{"a",2 },
{"c",3 },
};
// Use this for initialization
void Start () {
//var dicRe= dic.Reverse();
//var dicRe = dic.OrderByDescending(o => o.Key);
var dicRe = dic.OrderBy(o => o.Key);
foreach (var item in dicRe)
{
UnityEngine.Debug.Log(item.Key+":"+item.Value);
}
}
}
不过性能差异可能在
这个是string int 的字典 用.Reverse
image.png
这个是.OrderByDescending(o => o.Key) 他进行了排序后反转
image.png
然后还有个方法.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value)
是正序排列
image.png
其实完全没必要转换字典,因为foreach就能便利迭代器。
for循环我试过并没什么用因为即使反序,你的i也是从0开始根据key对应value