Linq/Lambda OrderBy Delegate for List of IP Addresses

前端 未结 6 633
粉色の甜心
粉色の甜心 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:20

    I would create a comparer for System.Net.IPAddress like so

    class IPAddressComparer : IComparer {
        public int Compare(IPAddress x, IPAddress y) {
            byte[] first = x.GetAddressBytes();
            byte[] second = y.GetAddressBytes();
            return first.Zip(second, (a, b) => a.CompareTo(b))
                        .FirstOrDefault(c => c != 0);
        }   
    }
    

    and then proceed as follows:

    var list = new List() {
        "192.168.0.1",
        "192.168.0.10",
        "192.168.0.2",
        "192.168.0.200"
    };
    var sorted = list.OrderBy(s => IPAddress.Parse(s), new IPAddressComparer());
    

提交回复
热议问题