user2818430
user2818430

Reputation: 6029

c# Dictionary<DateTime, List<Item>> order list by DateTime (nullable value)

I have a Dictionary<DateTime, List<Item>>

    Dictionary<DateTime, List<Item>> result =
        myList
            .GroupBy(k => new DateTime(k.Created.Value.Year, k.Created.Value.Month, 1))
            .OrderByDescending(k => k.Key)
            .ToDictionary(k => k.Key, v => v.ToList());

This will take a List<Item> groups it per year/month, order it descending (newest first) then creates a dictionary out of it.

My Question is: how can I OrderByDescending also the List within the Dictionary based on the the DateTime nullable (newest first)?

Upvotes: 1

Views: 2757

Answers (2)

Enigmativity
Enigmativity

Reputation: 117064

Try this:

Dictionary<DateTime, List<Item>> result =
    myList
        .GroupBy(k => new DateTime(k.Created.Value.Year, k.Created.Value.Month, 1))
        .OrderByDescending(k => k.Key)
        .ToDictionary(k => k.Key, v => v.OrderByDescending(x => x.Created).ToList());

Upvotes: 1

user2818430
user2818430

Reputation: 6029

I think I figured it out:

Dictionary<DateTime, List<Item>> result = myList.GroupBy(k => new DateTime(k.Created.Value.Year, k.Created.Value.Month, 1))
  .OrderByDescending(k => k.Key)
  .ToDictionary(k => k.Key, v => v.OrderByDescending(t => t.Published.GetValueOrDefault()).ToList());

Upvotes: 2

Related Questions