基于自定义条件使用LINQ OrderBy对地址列表按城市名称排序
Got it, let's tackle this custom sorting requirement where we need Address records ordered first by Lahore, then Islamabad, then Karachi (with any other cities trailing at the end). Here's how to do it cleanly with LINQ's OrderBy:
First, Fix Accessibility (Important!)
First off, your current Address and City classes have private fields for City and CityName—LINQ can't access private members directly, so we'll need to add public properties to expose them:
public class Address { public City City { get; set; } // Public property to access the City } public class City { public string CityName { get; set; } // Public property to access the CityName }
The Sorting Logic
We'll use a priority map (dictionary) to assign a numeric value to each target city—lower numbers mean higher priority. Then we'll sort the addresses based on this value.
Here's the full code:
// Define your priority order: Lahore = highest (0), Islamabad = next (1), Karachi = last (2) var cityPriorityMap = new Dictionary<string, int> { { "Lahore", 0 }, { "Islamabad", 1 }, { "Karachi", 2 } }; // Assume 'addresses' is your List<Address> var sortedAddresses = addresses.OrderBy(address => // Try to get the priority for the city; if not found, assign a higher number to put it at the end cityPriorityMap.TryGetValue(address.City.CityName, out int priority) ? priority : 3 // Any number higher than the max priority (2) works here ).ToList();
Bonus: Case-Insensitive Sorting
If you need to handle cases where CityName might be in lowercase/mixed case (e.g., "lahore" or "Islamabad"), just update the dictionary to use a case-insensitive comparer:
var cityPriorityMap = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase) { { "Lahore", 0 }, { "Islamabad", 1 }, { "Karachi", 2 } };
How It Works
- The dictionary maps each target city to a priority score: smaller scores get sorted first.
TryGetValuechecks if the current city exists in our priority list—if yes, we use its score; if not, we assign a higher score so non-target cities end up at the bottom.OrderByuses this score to sort theAddresslist exactly as you requested.
内容的提问来源于stack exchange,提问作者uinvent

