基于修改日期和创建日期对字典进行排序

本文关键字:创建日期 字典 排序 日期 于修改 修改 | 更新日期: 2023-09-27 18:11:41

我在字典中有一些记录,我需要根据创建日期(CDate)和修改日期(MDate)对数据进行排序。在创建记录时,我的CDate将具有当前日期时间,但MDate将为1/1/0001 12:00:00 AM。

这是用于排序的示例数据和代码。

CDate MDate
2013年4月30日下午4:43:41 PM
2013年4月30日下午4:43:28 PM
2013年4月30日下午4:43:54 PM
4/30/2013 5:03:13 PM 1/1/0001 12:00:00 AM

代码 :

FileSchedulerEntities = FileSchedulerEntities
                       .OrderByDescending(pair => pair.Value.MDate)
                       .ThenByDescending(pair => pair.Value.CDate)
                       .ToDictionary(pair => pair.Key, pair => pair.Value);

根据排序,我需要按降序排序数据,像这样。
CDate MDate
4/30/2013 5:03:13 PM 1/1/0001 12:00:00 AM
2013年4月30日下午4:43:41 PM
2013年4月30日下午4:43:28 PM
2013年4月30日下午4:43:54

但是前面提到的代码不能工作。什么好主意吗?

基于修改日期和创建日期对字典进行排序

字典中项的顺序根据文档未定义:

返回项的顺序未定义。

如果您需要一个允许通过键进行O(1)访问的结构,请使用Dictionary<TKey, TValue>
如果你需要一个有序的结构,使用List<KeyValuePair<TKey, TValue>>

试试SortedDictionary

你可以创建你自己的ToSortedDictionary<(这个IEnumerable源,Func keySelector, Func elementSelector, IEqualityComparer comparer):

public static SortedDictionary<TKey, TElement> ToSortedDictionary<TSource, TKey, TElement>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    Func<TSource, TElement> elementSelector,
    IEqualityComparer<TKey> comparer)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    if (keySelector == null)
    {
        throw Error.ArgumentNull("keySelector");
    }
    if (elementSelector == null)
    {
        throw Error.ArgumentNull("elementSelector");
    }
    var dictionary = new SortedDictionary<TKey, TElement>(comparer);
    foreach (TSource local in source)
    {
        dictionary.Add(keySelector(local), elementSelector(local));
    }
    return dictionary;
}