Conditional Select after GroupBy

How should I write a conditional Where after a GroupBy to Select items based on a if statement?

I have a List of objects of type Option:

class Option {
    public Boolean Important { get; set; }
    public int Priority { get; set; }
    public String Value { get; set; }
    public String Name { get; set; }
}

I initialize my Options and a list with all of them:

List<Option> myOptions = new List<Option> {
    new Option { Priority = 100, Name = "Color", Value = "Red", Important = true },
    new Option { Priority = 150, Name = "Color", Value = "Blue" },
    new Option { Priority = 100, Name = "Font", Value = "16" },
    new Option { Priority = 150, Name = "Font", Value = "32"
};

So I have Something like:

///MY Options///
/// NAME --- VALUE --- PRIORITY --- IMPORTANT
/// Color -- Red ----- 100----------True
/// Color -- Blue ---- 150----------False
/// Font-----16--------100----------False
/// Font-----32--------150----------False
/// 

I need to group them by Name and take those values based on two statements:

  1. Take the one with most priority having Important true.
  2. If there's no item with Important, take the one with most priority.

So the goal should be:

    ///Color - Red  //Because has the most priority being Important
    ///Font - 32    //Because has the most priority and there's no Important

I'm trying to avoid multiple iterations, so I'm building a Linq query... Without success.

.Select(g => new {
    Name = g.Key,
     Value = g.Where(op => op.Important).OrderByDescending(op => op.Priority).First().Value
}).ToList();

I don't know how to resolve the Where. Any idea?

Jon Skeet
people
quotationmark

It sounds like you don't really want to filter by "important" but order by it:

Value = g.OrderByDescending(op => op.Important) // true first
         .ThenByDescending(op => op.Priority)
         .First()
         .Value

people

See more on this question at Stackoverflow