List order based on several factors

Given the following classes:

public class Room
{
    public List<Person> People {get;set;}
    public string RoomType {get;set;}
}

public class Person
{
    public bool IsLead{get;set;}
}

Given that I have a list of rooms containing a list of people, how can I arrange them so that

  • The first room on the ordered list will be the one that contains the lead.
  • All numbers of the same type follow each other.

Please note that there is only one person who is headed.

Sample data:

  • doubleroom nonlead
  • singleroom nonlead
  • leadleroom lead
  • doubleroom nonlead

ordered:

  • leadleroom lead
  • singleroom nonlead
  • doubleroom nonlead
  • doubleroom nonlead
+4
source share
1 answer

Here's a simple, effective approach:

var orderedRooms = rooms
    .OrderBy(room => !room.People.Any(person => person.IsLead)) // room with lead will be first
    .GroupBy(room => room.RoomType) // RoomType with lead will be first
    .SelectMany(group => group); // flatten the list of groups into one list

This request meets the following requirements:

  • The first room on the ordered list is the one that contains the lead.
  • All numbers of the same type follow each other.

However, it does not sort room types in alphabetical order.

+4
source

Source: https://habr.com/ru/post/1526963/


All Articles