'C# - How to Order By in an ICollection?

I have an Applications table. An Application can have many ActivityPhases.

I use the following to display the latest ActivityPhase:

a.ApplicationActivityPhas.Where(aap => aap.ActivityPhas.WorkFlowStep == a.ApplicationActivityPhas.Max(x => x.ActivityPhas.WorkFlowStep)).Select(aap => aap.ActivityPhas.ActivityPhase)

Therefore, my Applications table only displays 1 ActivityPhase per Application record.

I have the following line that I am trying to use to order the ActivityPhase table column by:

data.OrderBy(a => a.ApplicationActivityPhas.FirstOrDefault().ActivityPhas.ActivityPhase);

The problem is that it is ordering the values within the ICollection. It does not order the values displayed in the Applications table.



Solution 1:[1]

First group by activity phase and select your maximum workflow step. Then select all the application phases that match this maximum workflow step.

a.ApplicationActivityPhas.GroupBy(aap => aap.ActivityPhase)
.Select(x => new { ActivityPhase = x.Key, MaxStep = x.Max(y => y.WorkFlowStep) })
.SelectMany(x => a.ApplicationActivityPhas.Where(y => y.WorkFlowStep == x.MaxStep && y.ActivityPhase == x.y.ActivityPhase))

Solution 2:[2]

The reason that my ordering was not working as expected is that the first ActivityPhase value was being used to determine the order, which was not always the correct one.

To grab the correct value, I just added the where clause that I use to display the correct value in my table:

data.OrderBy(a => a.ApplicationActivityPhas.Where(aap => aap.ActivityPhas.WorkFlowStep == a.ApplicationActivityPhas.Max(x => x.ActivityPhas.WorkFlowStep)).FirstOrDefault().ActivityPhas.ActivityPhase);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wouter
Solution 2