You need to enable JavaScript to run this app. 如何用类MySQL FIELD的字符串列表实现C# LINQ排序
优惠活动
大模型
产品
解决方案
定价
更多

如何用类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.MaxValue fallback ensures any Division values not in your custom list (like "XXX") will appear last in the sorted results. If you want them to come first instead, use int.MinValue instead.
  • Case Sensitivity: If your Division values might have inconsistent casing (e.g., "abc" instead of "ABC"), modify the lookup to use lowercase:
    .OrderBy(item => divisionSortPriority.TryGetValue(item.Division.ToLowerInvariant(), out int priority) ? priority : int.MaxValue)
    
    Just make sure your dictionary keys are also lowercase in this case.
  • Descending Sort: If you need any property sorted in descending order (e.g., ImportDate newest first), use OrderByDescending or ThenByDescending instead.

内容的提问来源于stack exchange,提问作者Mike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:43:08