Сортировать список<T> по количеству свойств внутреннего списка
Я пытаюсь найти способ сортировки списка объектов, основанных на свойстве (которое представляет собой список) свойства (другой список). Вот мои объекты:
ComputerCard:
public partial class ComputerCard : XtraUserControl
{
public string ComputerName { get; set; }
public List<Role> CardRoles = new List<Role>();
//More properties that are omitted for brevity.
}
Роль:
public class Role
{
public string RoleName { get; set; }
public string ImageName { get; set; }
public List<DependentRole> DependentRoles { get; set; }
public List<AppToRun> AppsToRun { get; set; }
public Role()
{
if (AppsToRun == null)
AppsToRun = new List<AppToRun>();
if (DependentRoles == null)
DependentRoles = new List<DependentRole>();
}
}
DependentRole:
public class DependentRole
{
public string Name { get; set; }
}
В моей основной форме я объявил следующее:
List<ComputerCard> cards
Как вы видете, cards
может иметь 1 или много Role
и каждый Role
может иметь 0 или много DependentRole
, Итак, учитывая этот список, мне нужен способ заказать его DependentRole.Count
в порядке убывания. Я посмотрел и попробовал рекомендацию из этой ссылки SO - Как отсортировать список по количеству? но не повезло.
List<ComputerCard> cardz = cards.Where(c => c.LookUpEdit.EditValue != null).ToList();
cardz.Sort((a, b) => a.CardRoles.Count - b.CardRoles.Count);
Результаты:
Card: File Server
Role: Server
Dependent Roles: 0
Card: VCS Gateway
Role: File Server
Dependent Roles: 0
Card: domain.pc1.domain
Role: Pilot 1
Dependent Roles: 3
Card: domain.pc5.domain
Role: Local Controller
Dependent Roles: 1
Card: domain.pc3.domain
Role: Pilot 3
Dependent Roles: 3
Card: domain.pc4.domain
Role: Ground Controller
Dependent Roles: 2
И что мне нужно, чтобы результаты выглядели так:
Card: File Server
Role: Server
Dependent Roles: 0
Card: VCS Gateway
Role: File Server
Dependent Roles: 0
Card: domain.pc5.domain
Role: Local Controller
Dependent Roles: 1
Card: domain.pc4.domain
Role: Ground Controller
Dependent Roles: 2
Card: domain.pc1.domain
Role: Pilot 1
Dependent Roles: 3
Card: domain.pc3.domain
Role: Pilot 3
Dependent Roles: 3
Обратите внимание, как карты перечислены по количеству зависимых ролей. Можно ли этого достичь? Если так, то как?
ОБНОВИТЬ
Используя ответ Амита, я получаю правильные результаты, но пренебрегаю требованием перечисления карт с несколькими ролями в порядке возрастания на DependentRoles. Count:
Card: File Server
Role: Server
Dependent Roles: 0
Card: VCS Gateway
Role: File Server
Dependent Roles: 2
Card: domain.pc1.domain
Role: Pilot 1
Dependent Roles: 3
Card: domain.pc4.domain
Role: Pilot 1
Dependent Roles: 3
Card: domain.pc2.domain
Role: Pilot 1
Dependent Roles: 3
Card: domain.pc5.domain
Role: Pilot 1
Dependent Roles: 3
Role: Ground Controller
Dependent Roles: 2
Card: domain.pc3.domain
Role: Pilot 1
Dependent Roles: 3
Role: Ground Controller
Dependent Roles: 2
Role: VCS Gateway
Dependent Roles: 0
2 ответа
Я думаю, что вам нужно следующее - (если нет, то дайте мне знать)
List<ComputerCard> SortedCards = cards.OrderBy(
x => x.CardRoles.Sum(y => y.DependentRoles.Count))
.ToList();
foreach (var item in SortedCards)
{
item.CardRoles = item.CardRoles
.OrderByDescending(x => x.DependentRoles.Count).ToList();
}
Попробуй это:
var ordered = cards.SelectMany(c => c.CardRoles.Select(r => new { Card = c, Role = r }))
.OrderBy(a => a.Role.DependentRoles.Count)
.ThenBy(a => a.Card.ComputerName)
.ThenBy(a => a.Role.RoleName)
.Select(c => c.Card);