0

I have a dictionary of lists of (1 or 2) objects; something like this:

var groupedFoos = Dictionary<string, List<Foo>>();

where the Dictionary key is an ID that's the common ID of the objects in the List. The object looks like this:

public class Foo 
{
    public string ID {get; set;}
    public enum Priority {get; set;} // High=0 or Low=1
    public int Score {get; set;}
}

A List<Object> can have only High Priority, only Low or both. The final order needs to have the same layout, but with order, so as IOrderedEnumerable<KeyValuePair<string, IOrderedEnumerable<Foo>>> where the order is:

  1. Highest Score of High Priority
  2. High + Low before Only High
  3. Highest Score of Low Priority

This is a working solution, but I'm not sure if there's a more efficient way:

// order each list so that High Priority comes before Low
var orderedFoos = groupedFoos
    .ToDictionary(group => group.Key, group => group.Value
        .OrderBy(foo => foo.Priority));

return orderedFoos
    .OrderByDescending(group => group.Value.Count(foo => foo.Priority == High)) // the ones with High Priority first
    .ThenByDescending(group => group.Value.First().Score) // Highest Priority first
    .ThenByDescending(group => group.Value.Count)); // the ones that have both first
e700k
  • 136
  • 2
  • 14
  • Remove the `.ToList() ` – Aluan Haddad Jan 22 '21 at 15:57
  • You say "The final order" - the final order of what? A `Dictionary<,>` has no order. Your `orderedFoos` seems to have nothing to do with your problem description??? – NetMage Jan 22 '21 at 19:04
  • Right, the returned object will not be modified further, but I understand that in order to safely retain the order I have to keep it as `IOrderedEnumerable>>` – e700k Jan 22 '21 at 19:45

0 Answers0