Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 716
lukiffer Avatar asked Jan 24 '11 17:01

lukiffer


2 Answers

You need to make a comparer: (Tested)

class IPComparer : IComparer<string> {
    public int Compare(string a, string b) {
        return Enumerable.Zip(a.Split('.'), b.Split('.'), 
                             (x, y) => int.Parse(x).CompareTo(int.Parse(y)))
                         .FirstOrDefault(i => i != 0); 
    }
}

You can then write

ips.OrderBy(p => p, new IPComparer()) 
like image 170
SLaks Avatar answered Sep 27 '22 20:09

SLaks


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());
like image 33
jason Avatar answered Sep 27 '22 19:09

jason