Alex Rivera | Logout

Linq/Lambda OrderBy Delegate for List<string> of IP Addresses

Asked 2011-01-24T17:47:07.573
15

Given List<string> ips = new List<string>();

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

Currently (and correctly, alphabetically) if the list contains:

192.168.0.1
192.168.0.2
192.168.0.10
192.168.0.200

ips.OrderBy(p => p) returns:

192.168.0.1
192.168.0.10
192.168.0.2
192.168.0.200
Edit
Report

1 Answer

7

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

class IPAddressComparer : IComparer<IPAddress> {
    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<string>() {
    "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());
answered 2011-01-24T18:09:40.130

Your Answer