notAnonymousAnymore
notAnonymousAnymore

Reputation: 2687

LINQ ordering with multiple joins

Basic schema that I have inherited (no foreign keys):

Tasks (TaskID, Description, ElementID, UserID)
Elements (ElementID, Description)
Users (UserID, FirstName, LastName)

I need to order a List<Task>, first by Element.Description, then by User.FirstName, then by User.LastName

I've managed so far to order by Element.Description using the following:

List<Task> tasks = db.Tasks.ToList();
List<Element> elements = db.Elements.ToList();
List<User> users = db.Users.ToList();    

tasks = tasks.Join(elements,
    t => t.ElementID,
    e => e.ElementID,
    (t, e) => new { t, e })
    .OrderBy(m => m.e.Description)
    .Select(m => m.t).ToList();

How do I join/order with more than one other entity? (ie. I need to add users to the above query and order by its fields)

(I know query syntax might be more suitable for joins but I've become more familiar/comfortable with lambda syntax, so it would be preferred)

Upvotes: 1

Views: 196

Answers (1)

Julien Roncaglia
Julien Roncaglia

Reputation: 17837

You first need to Join the result of your first Join with the list of User, then use ThenBy to order by the User fields :

tasks = tasks
    .Join(elements,
        t => t.ElementID,
        e => e.ElementID,
        (t, e) => new { t, e })
    .Join(users,
        x => x.t.UserID,
        u => u.UserID,
        (x, u) => new { x.t, x.e, u })
    .OrderBy(m => m.e.Description)
    .ThenBy(m => m.u.FirstName)
    .ThenBy(m => m.u.LastName)
    .Select(m => m.t)
    .ToList();

Upvotes: 1

Related Questions