排序基于价值SortedDictionary,键入不 [英] Sorting a SortedDictionary based on value, not key
问题描述
我有一个SortedDictionary,关键是一个int值和匹配值,每个键是一个类的对象。该类包含一个int和两个日期时间变量。
我需要根据班上银泰日期时间我SortedDictionary进行排序。所以,当我通过我的SortedDictionary做一个foreach循环,我将让他们排序依据日期时间。
这可能吗?我怎样才能实现呢?
输入代码在这里
类Busdetail
{
公众诠释BUSNO {搞定;组; }
公众的DateTime银泰{搞定;组; }
公众的DateTime OutTime {搞定;组; }
}
排序字典永远排序上的键,所以没有办法因此它们在其他的键的任何排序,重新安排它的数据。你可以做的是获取数据到另一个结构(某种 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
其中任何两个集合的,或者你可以将它们绑定到网格的数据源。
I have a SortedDictionary, the key is a int value and the matching value to each key is a class object. The class contains a int and a two datetime variable.
I need to sort my SortedDictionary based on the InTime datetime in my class. So that when I do a foreach to loop through my SortedDictionary I will have them sorted based on datetime.
Is this possible? How can I achieve it?
enter code here
class Busdetail
{
public int BusNo { get; set; }
public DateTime InTime { get; set; }
public DateTime OutTime { get; set; }
}
Sorted Dictionary will always sort on the key, so there is no way to re-arrange it's data so they are sorted on anything other that the key. What you can do is get the data into another structure (some kind of IOrderedEnumerable
) where they can be sorted on things other that the key.
If you want to discard the keys and just get the values then
var sortedValues = dictionary.Values.OrderBy(busDetail => busDetail.InTime);
will work, and the type of sortedValues will be IOrderedEnumerable<BusDetail>
.
If you still need to keep both the keys and values, you could do:
var sortedElements = dictionary.OrderBy(kvp => kvp.Value.InTime);
which will return a IOrderedEnumerable<KeyValuePair<int, BusDetail>>
.
You can that foreach
on any of these two collections, or you could bind them to a grid's datasource.
这篇关于排序基于价值SortedDictionary,键入不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!