Home > Net >  How to use the Max Value from a Collection in a C# Where Clause?
How to use the Max Value from a Collection in a C# Where Clause?

Time:04-06

I have a collection of activity phases. I want to get only one activity phase. That activity phase needs to be the one with the highest workflow step value. I tried the following, but no luck:

ActivityPhases = a.ApplicationActivityPhas
                 .Where(w => w.ActivityPhas.WorkFlowStep == Max(w.ActivityPhas.WorkFlowStep))
                 .(Select(p => p.ActivityPhas.ActivityPhase)

"Max" does not exist in the current context.

CodePudding user response:

First, get the max value, then get the object that have the max value.

var maxValue = a.ApplicationActivityPhas.Max(w => w.ActivityPhas.WorkFlowStep);
var activityPhases = a.ApplicationActivityPhas.Where(w => w.ActivityPhas.WorkFlowStep == maxValue);

If you have only one activity with the max value, you can use First instead.

var activityPhase = a.ApplicationActivityPhas.First(w => w.ActivityPhas.WorkFlowStep == maxValue);

CodePudding user response:

Is using .Where() a requirement? The title states it, but according to the question phrasing, it does not look like it is. If this answer is inappropriate due to it being a requirement, please let me know, and I will remove it.

.NET Framework 4.8

You could order your activity phases by their respective ActivityPhas.WorkFlowStep value in descending order, and then select the first activity phase:

var activityPhase = a.ApplicationActivityPhas
    .OrderByDescending(aap => aap.ActivityPhas.WorkFlowStep)
    .First();

Example fiddle here.

.NET 6

I think you could achieve what you want by using the .MaxBy() operator. It lets you define e.g. which property to use as the comparison value for each object, and returns the first object with the maximum value for that specific property.

var activityPhase = a.ApplicationActivityPhas
    .MaxBy(aap => aap.ActivityPhas.WorkFlowStep);

Example fiddle (using a random class) here.

  • Related