Skip to main content
 首页 » 编程设计

c#之如何在c#中的ipaddress数组中按升序排列所有ip地址

2024年02月20日14telwanggs

如何在c#中将ipaddress数组中的所有ipaddress按升序排列 我有一组 ipaddress 类

ipaddress[] device = new ipaddress[10]; 

它有不同的ip值,我想按升序排列

请您参考如下方法:

您可以使用版本技巧:

示例数据:

IPAddress[] ips = new[]{ 
        IPAddress.Parse("192.168.1.4"), 
        IPAddress.Parse("192.168.1.5"), 
        IPAddress.Parse("192.168.2.1"), 
        IPAddress.Parse("10.152.16.23"), 
        IPAddress.Parse("69.52.220.44"), 
    }; 

顺序升序:

var sortedIps = ips 
    .Select(ip => Version.Parse(ip.ToString())) 
    .OrderBy(v => v) 
    .Select(v => IPAddress.Parse(v.ToString())) 
    .ToArray(); 

结果:

{10.152.16.23}  System.Net.IPAddress 
{69.52.220.44}  System.Net.IPAddress 
{192.168.1.4}   System.Net.IPAddress 
{192.168.1.5}   System.Net.IPAddress 
{192.168.2.1}   System.Net.IPAddress 

更新

You: It give this error 'System.Version' does not contain a definition for 'Parse'. Me: Then you're not using at least .NET framework 4.0. Version.Parse You: Yes I am using .NET framwork 3.5 So What change I will need to do?

然后你可以使用IPAddress.GetAddressBytes对于Enumerable.OrderBy/ThenBy:

sortedIps = ips 
    .Select(ip => new { IP = ip, Bytes = ip.GetAddressBytes() }) 
    .OrderBy(x => x.Bytes[0]).ThenBy(x => x.Bytes[1]).ThenBy(x => x.Bytes[2]).ThenBy(x => x.Bytes[3]) 
    .Select(x => x.IP) 
    .ToArray(); 

更新2

Thanks, but it t stops if any member of array is null.if we want to work with that array which contains some null value. I want to order null values last.

然后使用此查询,它使用 Byte[] 和 Byte.MaxValue 作为空值:

var sortedIps = ips 
    .Select(ip => new {  
        IP = ip, 
        Bytes = ip == null 
            ? new[] { Byte.MaxValue, Byte.MaxValue, Byte.MaxValue, Byte.MaxValue } 
            : ip.GetAddressBytes()  
    }) 
    .OrderBy(x => x.Bytes[0]).ThenBy(x => x.Bytes[1]).ThenBy(x => x.Bytes[2]).ThenBy(x => x.Bytes[3]) 
    .Select(x => x.IP) 
    .ToArray();