C# - How to Order By in an ICollection?

186 views Asked by At

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.

2

There are 2 answers

0
Wouter On

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))
0
AudioBubble On

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);