dictionary 排序方法

假设有这样的乱序dictionary

            Dictionary<string, double> d_Last10Mins_RQIM = new Dictionary<string, double>();
            d_Last10Mins_RQIM.Add("1", 10.0);
            d_Last10Mins_RQIM.Add("2", 20.0);
            d_Last10Mins_RQIM.Add("3", 30.0);
            d_Last10Mins_RQIM.Add("4", 90.0);
            d_Last10Mins_RQIM.Add("5", 11.0);
            d_Last10Mins_RQIM.Add("6", 23.0);

如果想按照 value 排序 , 可以

            var Last10MinsSortedDict = (from entry in d_Last10Mins_RQIM orderby entry.Value ascending select entry)
                 .ToDictionary(pair => pair.Key, pair => pair.Value);

 

Last10MinsSortedDict 就是排序后的dictionary , 可以像这样引用

                       var first = Last10MinsSortedDict.First();
                       string firstVendor = first.Key;

                       var last = Last10MinsSortedDict.Last();
                       string lastVendor = last.Key;

或者foreach

                       foreach (var pair in Last10MinsSortedDict)
                       {
             }

 

要逆序排就把 ascending  改为 descending

 

posted on 2014-02-11 15:37  齐文宣  阅读(7370)  评论(0)    收藏  举报

导航