对字符串使用自定义比较器

新手

我有以下清单:

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);

看起来好像可行,是否有必要编写像这样的自定义比较器

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));
        }
 }
现在住

试试这个例子。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章