2010-08-05 187 views
4

我有一個SortedDictionary,鍵是一個int值,每個鍵的匹配值是一個類對象。該類包含一個int和一個兩個datetime變量。基於值排序SortedDictionary,而不是鍵

我需要根據我的類中的InTime日期時間對我的SortedDictionary進行排序。所以當我做一個foreach循環訪問SortedDictionary時,我會根據datetime對它們進行排序。

這可能嗎?我怎樣才能實現它?

enter code here 
class Busdetail 
    { 
     public int BusNo { get; set; } 
     public DateTime InTime { get; set; } 
     public DateTime OutTime { get; set; } 
    } 
+0

可能的重複http://stackoverflow.com/questions/289/how-do-you-sort-ac-dictionary-by-value – WildCrustacean 2010-08-05 17:20:48

+0

可能重複的[.NET SortedDictionary,但按值排序](http:/ /stackoverflow.com/questions/2619051/net-sorteddictionary-but-sorted-by-values) – nawfal 2014-05-22 05:28:46

回答

11

排序字典永遠排序的關鍵,所以沒有辦法所以他們對其他的關鍵任何分類重新安排它的數據。你可以做的是將數據導入另一個結構(某種IOrderedEnumerable),在那裏它們可以在其他事物上進行排序。

如果你要放棄鍵和剛剛得到的值,然後

var sortedValues = dictionary.Values.OrderBy(busDetail => busDetail.InTime); 

會的工作,並sortedValues的類型將是IOrderedEnumerable<BusDetail>。 如果你仍然需要保持這兩個鍵和值,你可以這樣做:

var sortedElements = dictionary.OrderBy(kvp => kvp.Value.InTime); 

將返回一個IOrderedEnumerable<KeyValuePair<int, BusDetail>>。 您可以在這兩個集合中的任何一個集合上使用foreach,也可以將它們綁定到網格的數據源。

+0

要每次進入或從中刪除字典時排序字典? – shinzou 2017-04-09 19:32:49

2

SortedDictionary不能按值排序,儘管您可以提取排序的值列表,正如其他答案指出的那樣。

你想要做的是使用keyvaluepairs的列表,而不是,然後進行排序,像這樣:

List<KeyValuePair<int, BusDetail>> busses = GetMyListOfBusses(); 
busses.Sort((first, next) => { 
    return first.Value.InTime.CompareTo(next.Value.Intime); 
}); 

在這一點上,公共汽車的你keyvaluepair名單將由銀泰

1

我整理認爲你可以使用SortedSet和Tuple的鍵和值,如: SortedSet>((a,b)=>(a.Item2.CompareTo(b.Item2));

0

您可以使用Linq查詢。

var D = new SortedDictionary<int, string>(); 
var qD = from kvp in D 
     orderby kvp.Value 
     select kvp 
;