2011-08-26 127 views
1

我有一个struct Test,它作为值添加到字典中。 我想要做的是按值的日期时间对字典进行排序。使用DateTime对象对值字典进行排序

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选择一个对象,但也能够迭代并按照datetime的顺序出现。

+1

也许你已经知道了:它不是C#字典,它是一个.NET字典。 –

+0

...使用OrderedDictionary? –

+0

为什么你想排序字典?我没有任何意义。你的意思是你想检索字典的所有值,按其成员之一的值进行排序? – Tipx

回答

2

“排序字典”是什么意思?字典本身没有“订单”。它是一个密钥集合,其底层实现是一个哈希表。

我假定你的意思是说:“我想按照值的顺序列举字典的内容。”这可以这样做:

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) ; 
} 

如果另一方面,你真的想要/需要一个有序集合,你需要指出你的实际要求是什么。

+0

谢谢!我用你的代码来创建一个返回新字典的排序方法。不知道这是否是最好的方法,但它的工作:)'公共字典排序(字典<字符串,测试>字典) { Dictionary temp = new Dictionary ( ); foreach(KeyValuePair entry in dict.OrderBy(x => x.Value.dt).ThenByDescending(x => x.Key)) temp.Add(entry.Key,entry.Value) ; } return temp; }' – Rob

1

字典固有地未排序。有IDictionary的排序实现,但它们通常按键排序,而不是值(或值的属性)。如果您需要在值的DT字段排序的值,你可以这样做:

var valuesSorted = dict.Values.OrderBy(v=>v.dt); 

但是,这消除了字典。我怀疑你需要一个不同的数据结构,但是我们需要更多地了解用例以确定是什么。

0

根据你的问题和其他人指出的,字典没有排序,所以返回排序字典的唯一合乎逻辑的方法是真正返回排序的IEnumerable<KeyValuePair<String, Test>>。做这件事很简单。

var query = 
    from kvp in dict 
    orderby kvp.Value.dt 
    select kvp; 

你可以很容易地改变select表达式返回KeyValuePair<,>的值部分或代替返回一个匿名类型。

相关问题