Ordering a list based on multiple factors

.net, c#, linq

Solution

Here's a simple, efficient 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 query meets the following requirements:

- The first room in the ordered list is the one that the lead is in.

- All rooms of the same type follow each other.

However, it does not sort the room types alphabetically.

Problem

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 I have a list of Rooms that contains a list of People, how can I order them in such a way that - The first room in the ordered list be the one that the lead is in. - All rooms of the same type follow each other Note that there is only ever one person who is lead. Example data: - doubleroom nonlead - singleroom nonlead - singleroom lead - doubleroom nonlead ordered: - singleroom lead - singleroom nonlead - doubleroom nonlead - doubleroom nonlead

Original source