首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

List 排序擴展方法實作(中):Rank 核心演算法與動態型別整合

     編輯:關於C語言

前置準備回顧

已完成動態建立類型、設值、取值、取得屬性中繼資料四大核心方法,現著手實作排序核心邏輯。

設計決策:委派而非介面

比較邏輯採用 `Comparison` 委派而非 `IComparer` 介面,提供更靈活的使用方式,呼叫端可直接傳入 Lambda 表達式。

Rank 擴展方法完整實作

public static IEnumerable Rank(this IEnumerable value, Comparison comparison, string orderName) where T : class
{
    string orderColumn = "Rank";
    if (!string.IsNullOrEmpty(orderName))
        orderColumn = orderName;

    List list = value.ToList();
    list.Sort(comparison);      // 升序排序
    list.Reverse();             // 反轉為降序

    List returnList = new List();
    int order = 1;
    int pcount = 0;             // 並列計數器

    // 建構動態型別:原型別屬性 + 排名欄位
    Dictionary dictionaryType = TypeTransform(typeof(T));
    dictionaryType.Add(orderColumn, typeof(int).FullName);
    Type type = DynamicCreateType(dictionaryType, new string[] { "System.dll", "System.Core.dll" });

    for (int i = 0; i < list.Count; i++)
    {
        // 取得原物件屬性值
        Dictionary tempRank = DynamicGetProperty(list[i]);
        tempRank.Add(orderColumn, order);  // 加入名次
        returnList.Add(DynamicSetProperty(type, tempRank));

        if (i < list.Count - 1)
        {
            int result = comparison(list[i], list[i + 1]);
            
            if (result != 0)  // 不相等
            {
                if (pcount == 0)
                    order++;
                else
                {
                    order = order + 1 + pcount;  // 跳過並列佔用的名次
                    pcount = 0;
                }
            }
            else  // 相等(並列)
            {
                pcount++;
            }
        }
    }
    return returnList;
}


演算法關鍵點解析

  • 雙階段排序:Sort(升序) + Reverse(降序),符合薪資高者優先習慣
  • 動態型別建構:Runtime 建立含排名欄位的新型別,保留原資料結構
  • 並列排名邏輯:pcount 累計並列筆數,名次計算 `order + 1 + pcount` 正確跳過被佔用名次
  • 委派彈性:呼叫端決定比較邏輯,支援多欄位、複雜排序規則
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved