Linq/Lambda OrderBy Delegate for List of IP Addresses

前端 未结 6 681
粉色の甜心
粉色の甜心 2021-01-01 21:34

Given List ips = new List();

I need to sort the list of IP addresses in a logical order (i.e. \"192.168.0.2\" comes before \

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-01 22:29

    This is an old question but I was looking up IP Comparer's and it came up. I wanted something that worked for IPv6 as well though so once I got it I thought I'd add it here for the next person who does a search for it. Much like SLaks's answer, I agree that an IComparer is probably best.

    public class IPComparer : IComparer
    {
        public int Compare(IPAddress x, IPAddress y)
        {
            if (ReferenceEquals(x, null))
                throw new ArgumentNullException("x");
    
            if (ReferenceEquals(y, null))
                throw new ArgumentNullException("y");
    
            return BitConverter.ToUInt32(x.GetAddressBytes().Reverse().ToArray(),0)
                .CompareTo(BitConverter.ToUInt32(y.GetAddressBytes().Reverse().ToArray(),0));
        }
    }
    

    Nothing fancy but it should work.

提交回复
热议问题