2010-08-05 181 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 
;