How to sort list of Ip Addresses using c#

前端 未结 4 948
抹茶落季
抹茶落季 2020-12-01 05:43

I\'ve a list of IP addresses as follows

192.168.1.5
69.52.220.44
10.152.16.23
192.168.3.10
192.168.1.4
192.168.2.1

I\'m looking for such a

4条回答
  •  鱼传尺愫
    2020-12-01 06:13

    You may find this function useful too.

    public static class ExtensionMethods
    {
      public static int CompareTo(this IPAddress x, IPAddress y)
      {
        var result = x.AddressFamily.CompareTo(y.AddressFamily);
        if (result != 0)
          return result;
    
        var xBytes = x.GetAddressBytes();
        var yBytes = y.GetAddressBytes();
    
        var octets = Math.Min(xBytes.Length, yBytes.Length);
        for (var i = 0; i < octets; i++)
        {
          var octetResult = xBytes[i].CompareTo(yBytes[i]);
          if (octetResult != 0)
            return octetResult;
        }
        return 0;
      }
    }
    

提交回复
热议问题