簡單的鍵值按值排序問題

2022-01-26 03:43:42 字數 1197 閱讀 2345

需求是這樣的:

這裡簡述一下:

乙個小小排序問題。。不是很高深的
用c#**實現,不要用linq技術

問題:廣東 30

湖南 20

廣西 60

北京 70

上海 30

排序之後:

北京 70

廣西 60

廣東 30

上海 30

湖南 20

這是乙個簡單的鍵值按值排序問題,難點在於不用linq(有的專案環境是.net 2.0),如果用linq很容易解決(在該問題的回覆中有,這裡就不說了),下面提供兩種方法。

方法一,建乙個只有key和value兩個屬性的實體,然後用氣泡排序,**如下:

class program

,new testmodel(),

new testmodel(),

new testmodel(),

new testmodel()

};testmodel temp = new testmodel();

for (int m = 0; m < tmlist.count; m++)}}

foreach (var item in tmlist)

console.read();}}

public

class testmodel

public

int count

}

這種方法容易理解,但要新建乙個實體比較麻煩。

如果在程式中只要做個簡單的排序這樣就顯得太複雜了,有沒有簡單的方法呢?我這裡提供另外一種思路,**如下:

class program

val = new dictionary();

foreach (var item in newval)

//val就是排序後的字典集合

console.read();}}

sealed

class reversecomparer: icomparerwhere t : icomparable

}

程式中也說了,

newval.add(item.value *

1000

+index, item.key);

這一行是關鍵,各位讀者自己思考一下為什麼可以這樣處理,這樣處理有什麼侷限性。

python按值排序 python 按值排序

感謝分享!python 字典 dict 的特點就是無序的,按照鍵 key 來提取相應值 value 如果我們需要字典按值排序的話,那可以用下面的方法來進行 1 下面的是按照value的值從大到小的順序來排序。dic dict sorted dic.iteritems key lambda d d 1...

使用TreeMap按值排序遇到的問題

如果我們需要乙個有序的map,我們會使用treemap進行儲存。treemap預設是按照key值公升序進行排序的,如數字 ascii。如果我們需要對treemap按值進行排序的話,可以例項化comparator介面,在treemap的構造方法中當作引數傳入。這裡遇到了問題 當插入treemap的兩條...

二維陣列按指定的鍵值排序

二維陣列按指定的鍵值排序 param array 需要排序的二維陣列 param keys 需要排序根據的索引 param string type 正序 倒敘 預設倒序 return array string public function array sort array,keys,type as...