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
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())
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With