2016-11-05 63 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

相关问题