user3788671
user3788671

Reputation: 2047

Using LINQ to order to different properties of an object

As of right now I am using LINQ to order a list of people in a phone book. Currently, I am ordering the list by branch and then by their full name (last,first). I am adding a new property to the person object called location which has the same values as the branch so I am going to want to include that into my LINQ statment but I am not sure how.

Here is what I currently have:

phoneList.OrderBy(e => branchOrder.IndexOf(e.Branch)).ThenByDescending(e => e.FirstName == null).ThenBy(e => e.FullName)

Within the LINQ statement you see the branchOrder.IndexOf function. BranchOrder is my defined list of all the branches in numeric/alphabetical order.

How can I OrderBy both branchOrder.IndexOf(e.Branch) and branchOrder.IndexOf(e.Location)?

Note: Location can be NULL but if it is not NULL then Location should be taken rather than e.Branch.

Upvotes: 1

Views: 62

Answers (2)

Rufus L
Rufus L

Reputation: 37020

Seems like a simple condition should work...

branchOrder.IndexOf(e.Location == null ? e.Branch : e.Location)

Upvotes: 3

The Vermilion Wizard
The Vermilion Wizard

Reputation: 5395

Use the null coalescing operator.

phoneList.OrderBy(e => branchOrder.IndexOf(e.Location ?? e.Branch))

Upvotes: 7

Related Questions