2016-11-05 62 views
0

我有下面的列表使用自定義比較:字符串

var ips = new List<string> { 
    "192.168.5.1", 
    "192.168.0.2", 
    "192.168.0.3", 
    "192.168.0.4", 
    "192.168.1.1", 
    "192.168.1.2", 
    "192.168.1.3", 
    "192.168.1.4" 
}.OrderBy(p => p.Ip); 

它看起來像它的工作原理,是否有必要編寫自定義比較喜歡this one

public class MyComparer : IComparer<string> 
{ 
     public int Compare(string x, string y) 
     { 
      int ip1 = IPAddress.Parse(x).ToInteger(); 
      int ip2 = IPAddress.Parse(y).ToInteger(); 
      return (((ip1 - ip2) >> 0x1F) | (int)((uint)(-(ip1 - ip2)) >> 0x1F)); 
     } 
} 
+0

好的。現在你的問題是什麼? –

+0

是的,它是必要的118.168.5.1 1.198.6.7。與此數據進行比較 –

+0

'.OrderBy(p => p)'是正確的命令,它不需要任何自定義比較器。 –

回答

0

嘗試這個例子。

192.168.0.1 
192.168.0.2 
192.168.0.10 
192.168.0.200 

如果你申請OrderBy,它會給你這個結果。

192.168.0.1 
192.168.0.10 
192.168.0.2 
192.168.0.200 

所以,你必須做出這樣下面的例子你自己的自定義比較。

https://stackoverflow.com/a/4785462/6527049

相關問題