C# LINQ Orderby on parent only in hierarchical parent-child relationship data

Viewed 541

I have an interesting problem in LINQ and I am not sure how to solve it. Here is what my data looks like

I have a list of Send objects(List<Send>) where Send object has the following properties

public class Send
{   
    public string messageName { get; set; }
    public string Port { get; set; }        
    public string Type { get; set; }
}

where Port can be PortA, PortB, etc. Type can only be "receive" or "transmit" and messageName can be

0_firstmessage
1_secondmessage
2_thirdmessage

messageName always have an identifier at the start 0,1,2....N.

My current list has data like the following. A few things to note in data

  1. My data is already sorted according to Ports. So, PortA data comes first followed by PortB.
  2. Each message of type "receive" is followed by 0 or N transmit messages group.
  3. Each transmit message always has a parent receive.

My data:

MESSAGENAME, PORT  , TYPE  
    - 0_message , PortA , receive
       - 1_message , PortA , transmit
       - 3_message , PortA , transmit
       - 7_message , PortA , transmit
    - 8_message , PortA , receive
       - 9_message , PortA , transmit

    - 2_message , PortB , receive
    - 4_message , PortB , receive
       - 5_message , PortB , transmit
       - 6_message , PortB , transmit
    - 10_message, PortB , receive
       - 11_message , PortB , transmit

My final output should be like this.

 MESSAGENAME, PORT  , TYPE  
- 0_message , PortA , receive
   - 1_message , PortA , transmit
   - 3_message , PortA , transmit
   - 7_message , PortA , transmit
- 2_message , PortB , receive
- 4_message , PortB , receive
   - 5_message , PortB , transmit
   - 6_message , PortB , transmit
- 8_message , PortA , receive
   - 9_message , PortA , transmit
- 10_message, PortB , receive
   - 11_message , PortB , transmit

I want to ORDERBY based on MESSAGE_NAME for "receive" type messages only. The child "transmit" messages should stay intact.

I searched alot online but I am not sure how to write this LINQ query.

Here is a example: You can play around here. https://dotnetfiddle.net/DKOOk2

4 Answers
Related