Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Select after GroupBy

Tags:

c#

lambda

linq

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?

like image 326
Mario Levrero Avatar asked Dec 02 '25 22:12

Mario Levrero


1 Answers

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
like image 56
Jon Skeet Avatar answered Dec 05 '25 11:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!