如何用类MySQL FIELD的字符串列表实现C# LINQ排序
Implement Custom Division Sorting (Like MySQL FIELD()) for List
Got it, let's break down how to achieve this custom multi-property sorting in C#—replicating the behavior of MySQL's FIELD() function for your Division field, followed by the other specified properties.
Step 1: Define Custom Division Priority Mapping
First, create a dictionary that maps each Division value to a numerical priority. This lets you control exactly the order you want (ABC first, then XYZ, DEF, HIJ):
// Define your custom Division sort order: ABC → XYZ → DEF → HIJ var divisionSortPriority = new Dictionary<string, int> { { "ABC", 1 }, { "XYZ", 2 }, { "DEF", 3 }, { "HIJ", 4 } };
Step 2: Sort the Collection with LINQ
Use LINQ's OrderBy (for the custom Division order) followed by ThenBy for the remaining properties. We'll use TryGetValue to safely handle any unexpected Division values (they'll get pushed to the end of the sorted list):
// Assuming your original collection is called workItemHeaders var sortedWorkItems = workItemHeaders // First sort by custom Division priority .OrderBy(item => divisionSortPriority.TryGetValue(item.Division, out int priority) ? priority : int.MaxValue) // Then sort by ImportDate ascending .ThenBy(item => item.ImportDate) // Next sort by OrderNumber (string comparison, adjust if needed) .ThenBy(item => item.OrderNumber) // Finally sort by LineNumber ascending .ThenBy(item => item.LineNumber) .ToList();
Key Notes:
- Handling Unexpected Divisions: The
int.MaxValuefallback ensures anyDivisionvalues not in your custom list (like "XXX") will appear last in the sorted results. If you want them to come first instead, useint.MinValueinstead. - Case Sensitivity: If your
Divisionvalues might have inconsistent casing (e.g., "abc" instead of "ABC"), modify the lookup to use lowercase:
Just make sure your dictionary keys are also lowercase in this case..OrderBy(item => divisionSortPriority.TryGetValue(item.Division.ToLowerInvariant(), out int priority) ? priority : int.MaxValue) - Descending Sort: If you need any property sorted in descending order (e.g.,
ImportDatenewest first), useOrderByDescendingorThenByDescendinginstead.
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

