mlg
mlg

Reputation: 1172

C# - Sort dictionary based on Modified date and created date

I have some records in dictionary, I need to sort the data based on Created Date (CDate) and Modified Date(MDate). While creating the record, my CDate will have current datetime, but MDate will be 1/1/0001 12:00:00 AM.

This is the sample data and code used for sorting.

CDate MDate
4/30/2013 4:43:41 PM 4/30/2013 4:46:47 PM
4/30/2013 4:43:28 PM 4/30/2013 4:46:36 PM
4/30/2013 4:43:54 PM 4/30/2013 4:46:16 PM
4/30/2013 5:03:13 PM 1/1/0001 12:00:00 AM

Code:

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

As per sorting, I need sorted data in descending order like this.
CDate MDate
4/30/2013 5:03:13 PM 1/1/0001 12:00:00 AM
4/30/2013 4:43:41 PM 4/30/2013 4:46:47 PM
4/30/2013 4:43:28 PM 4/30/2013 4:46:36 PM
4/30/2013 4:43:54 PM 4/30/2013 4:46:16 PM

But the aforementioned code is not working. Any ideas?

Upvotes: 2

Views: 607

Answers (2)

Paulo Morgado
Paulo Morgado

Reputation: 14846

Try a SortedDictionary.

You can create your own ToSortedDictionary<(this IEnumerable source, 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;
}

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

The order of items in a dictionary is undefined as per the documentation:

The order in which the items are returned is undefined.

If you need a structure that allows for O(1) access via a key, use Dictionary<TKey, TValue>.
If you need an ordered structure, use something like List<KeyValuePair<TKey, TValue>>.

Upvotes: 8

Related Questions