2012-07-11 70 views
5

我想對樹形視圖的節點進行排序,當然它們的文本屬性也是如此。問題是我的比較課不關心數字。下面是代碼:考慮數字的字符串比較

public class TreeNodeSorter : IComparer 
{ 
    public int Compare(object x, object y) 
    { 
     var tx = x as TreeNode; 
     var ty = y as TreeNode; 

     return string.Compare(tx.Text, ty.Text); 
    } 
} 

,這裏是結果:

enter image description here

第一個子節點(調試...)是確定的,但我的問題是,爲什麼地球上「HBM \ D10「在」HBM \ D7「之前排序,等等......

+1

可能的[C#中的自然排序順序]重複(http://stackoverflow.com/questions/248603/natural-sort-order-in-c-sharp) – Jon 2012-07-11 10:31:32

回答

0

http://www.dotnetperls.com/alphanumeric-sorting讀。您可能需要刪除其他所有內容,以便讓他們的解決方案發揮作用 - 因爲他們按數字或按字母順序排序。

如果它是一個動態文件名,最好使用正則表達式來匹配要排序的部分。

5

如果可移植性不是問題,則可以輸入/調用StrCmpLogicalW()。此功能用於Windows外殼程序將其顯示文件名排序:

public class TreeNodeSorter : IComparer 
{ 
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] 
    static extern int StrCmpLogicalW(string x, string y); 

    public int Compare(object x, object y) 
    { 
     var tx = x as TreeNode; 
     var ty = y as TreeNode; 

     return StrCmpLogicalW(tx.Text, ty.Text); 
    } 
} 
+0

取決於你想要的解決方案的'乾淨' 。可能性是,如果你使用DotNetPearls和正則表達式的方法實現你自己,你可能會學到更多,並且可能重用它。 – Echilon 2012-07-11 10:36:11

0

這是因爲char'1'少於char'7。這是因爲字符串每次只能比較一個字符。

一個簡單的辦法是在字符串的begininning到incude填補0的,如:

D04 
D07 
D10 
D11 

等等

0

如果你有一個合理的模式來提取數(我猜像@「\ D \ d +」)使用它從您的標籤中刪除數字,然後如果標籤是等於,則返回兩個數字的差異作爲比較。