LINQ中基于现有OrderBy逻辑添加ThenBy实现多条件排序的咨询
ThenBy Got it, let's sort this out! You're already using a switch statement to handle primary sorting via OrderBy/OrderByDescending, and now you want to add a secondary sort using Grade with ThenBy—that's totally straightforward once you know where to slot it in.
Approach 1: Add Secondary Sort to All Primary Scenarios (Most Efficient)
If you want the Grade sort to apply no matter which primary sort option is selected, handle the primary sort first in your switch, then append the secondary sort universally after the switch. This keeps your code DRY (Don't Repeat Yourself) since you don't have to duplicate the ThenBy line in every case.
Here's the updated code:
// First handle primary sorting based on filters.Sort switch (filters.Sort) { case "new": query = query.OrderByDescending(a => a.CreatedAt); break; case "old": query = query.OrderBy(a => a.CreatedAt); break; case "salary-asc": query = query.OrderBy(a => a.Profile.CompensationTypeRate.FromCompensation); break; // Always add a default case to handle unexpected Sort values default: query = query.OrderByDescending(a => a.CreatedAt); // Fallback to "new" sort break; } // Now add the secondary sort by Grade (use ThenByDescending if you want descending order) query = query.ThenBy(a => a.Grade);
How This Works
- The
OrderBy/OrderByDescendingsets the primary sort order (your original logic). ThenByadds a secondary sort: when two items have the same value for the primary sort field (e.g., sameCreatedAtdate), they'll be sorted byGradenext.
Approach 2: Add Secondary Sort Only to Specific Primary Scenarios
If you only want the Grade sort to apply to certain primary sort options, embed the ThenBy directly inside the relevant cases. This gives you more control over which scenarios use the secondary sort.
Example:
switch (filters.Sort) { case "new": query = query.OrderByDescending(a => a.CreatedAt) .ThenBy(a => a.Grade); // Add secondary sort here break; case "old": query = query.OrderBy(a => a.CreatedAt); // No secondary sort for this case break; case "salary-asc": query = query.OrderBy(a => a.Profile.CompensationTypeRate.FromCompensation) .ThenByDescending(a => a.Grade); // Use descending for Grade here break; default: query = query.OrderByDescending(a => a.CreatedAt); break; }
Key Notes
- Always use
ThenBy/ThenByDescendingafter an initialOrderBy/OrderByDescending—they can't be used alone to start a sort chain. - Choose
ThenByfor ascending order (default) orThenByDescendingfor descending order based on your requirements for theGradefield.
内容的提问来源于stack exchange,提问作者Jalle

