我有一个结构测试,我将其作为值添加到字典中。 我想要做的是按值的日期时间对字典进行排序。
struct Test
{
DateTime dt;
public string ID;
}
Dictionary<String, Test> dict = new Dictionary<String,Test>();
Test t = new Test();
t.dt = DateTime.Now;
t.ID = "XUDF";
dict.Add(t.ID, t);
t.dt = DateTime.Now.AddDays(17);
t.ID = "RFGT";
dict.Add(t.ID, t);
t.dt = DateTime.Now.AddDays(3);
t.ID = "ADLV";
dict.Add(t.ID, t);
t.dt = DateTime.Now.AddHours(2);
t.ID = "SKFU";
dict.Add(t.ID, t);
我不确定这之后要做什么。 另外,这是最好的方法吗? 我正在使用 .net 3
我想要做的是有一个列表,我可以通过 ID 访问它,但也可以按 t.dt 中的日期时间排序。 我希望能够通过 ID 选择一个对象,但也能够遍历并让它按日期时间顺序出现。
最佳答案
“字典排序”是什么意思?字典本身没有“顺序”。它是一个键控集合,其底层实现是一个哈希表。
我假设您的意思是,“我想按值的顺序枚举字典的内容。”可以这样做:
public void List( Dictionary<string,DateTime> dict )
{
int i = 0 ;
foreach( KeyValuePair<string,DateTime> entry in dict.OrderBy( x => x.Value ).ThenByDescending( x => x.Key ) )
{
Console.WriteLine( "{0}. Key={1}, Value={2}" , ++i , entry.Key , entry.Value ) ;
}
Console.WriteLine( "The dictionary contained a total of {0} entries." , i ) ;
}
如果另一方面,您确实想要/需要一个有序的集合,则需要说明您的实际需求是什么。
关于c# - 按值对字典进行排序,该值是具有 DateTime 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7198724/