How to sort list of Ip Addresses using c#

前端 未结 4 929
抹茶落季
抹茶落季 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:03

    This might look as a hack, but it does exactly what you need:

    var unsortedIps =
        new[]
        {
            "192.168.1.4",
            "192.168.1.5",
            "192.168.2.1",
            "10.152.16.23",
            "69.52.220.44"
        };
    
    var sortedIps = unsortedIps
        .Select(Version.Parse)
        .OrderBy(arg => arg)
        .Select(arg => arg.ToString())
        .ToList();
    
    0 讨论(0)
  • 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;
      }
    }
    
    0 讨论(0)
  • 2020-12-01 06:15

    You can convert each IP address into an integer like so ...

    69.52.220.44 =>
    
    69 * 255 * 255 * 255 +
    52 * 255 * 255 +
    220 * 255 +
    44
    

    Then sort by the integer representation.

    0 讨论(0)
  • 2020-12-01 06:24

    You can use the Array.Sort function with a function we will create for comparing two IPs:

    //ips is string array
    Array.Sort(ips, IpCompare);
    

    And then put this function in the code.

    private static int IpCompare(string x, string y)
        {
            string ip1 = x + '.', ip2 = y + '.';
            string xSection = "", ySection = "";
            for (int i = 0; i < ip1.Length && i < ip2.Length; i++)
            {
                if (ip1[i] == '.' && ip2[i] == '.')
                {
                    if (xSection != ySection)
                        return int.Parse(xSection) - int.Parse(ySection);
                    xSection = ""; // Start compare the next section
                    ySection = "";
                }
                else if (ip1[i] == '.') return -1; //The first section is smaller because it's length is smaller
                else if (ip2[i] == '.') return 1;
                else
                {
                    xSection += ip1[i];
                    ySection += ip2[i];
                }
            }
            return 0; 
            //If we would find any difference between any section it would already return something.
            //so that mean that both IPs are the same
       }
    
    0 讨论(0)
提交回复
热议问题