LINQ,与count和orderby的双连接

时间:2017-10-30 14:57:35

标签: c# linq lambda

LINQ新手在查询中苦苦挣扎,这在常规SQL中非常容易,但由于某些原因导致我在尝试用lambda / query表达时感到非常痛苦。

我有三个对象: 组织

public class Organization
{
    public int OrganizationId { get; set; }
    public ICollection<Employee> Employees { get; set; }
}

员工

public class Employee
{
    public int EmployeeId { get; set; }
    public Organization Organization { get; set; }
    public ICollection<Ticket> Tickets { get; set; }
}

票务

public class Ticket
{
    public int TicketId { get; set; }
    public Employee Employee { get; set; }
}

使用LINQ,我需要按照他们拥有的票数来检索一个有序的组织列表,最好是IQueryable。

这是我到目前为止所提出的:

var q = Organizations.Join
                    (
                        Employees,
                        org => org.OrganizationId,
                        emp => emp.Organization.OrganizationId,
                        (org, emp) => new {org, emp}
                    )
                    .Join
                    (
                        Tickets,
                        t => t.emp.EmployeeId,
                        ticket => ticket.Employee.EmployeeId,
                        (t, ticket) => new {t, ticket}
                    )
                    .GroupBy(t => t.t.org.OrganizationId)
                    .Select
                    (
                        t => new { OrganizationId = t.Key, TCount = t.Count() }
                    )
                    .OrderByDescending(t => t.TCount).Dump()

所以我拥有组织的ID和计数。我该如何检索完整的组织对象?

1 个答案:

答案 0 :(得分:2)

由于每个班级都有收藏品,因此您不需要使用加入。

Organizations.OrderByDescending(o => o.Employees.Sum(e => e.Tickets.Count()));