I have following list:
var ips = new List<string> {
"192.168.5.1",
"192.168.0.2",
"192.168.0.3",
"192.168.0.4",
"192.168.1.1",
"192.168.1.2",
"192.168.1.3",
"192.168.1.4"
}.OrderBy(p => p.Ip);
It looks like it works, Is it necessary to write a custom comparer like this one:
public class MyComparer : IComparer<string>
{
public int Compare(string x, string y)
{
int ip1 = IPAddress.Parse(x).ToInteger();
int ip2 = IPAddress.Parse(y).ToInteger();
return (((ip1 - ip2) >> 0x1F) | (int)((uint)(-(ip1 - ip2)) >> 0x1F));
}
}
try this example.
192.168.0.1
192.168.0.2
192.168.0.10
192.168.0.200
If you apply OrderBy
, It will give you this result.
192.168.0.1
192.168.0.10
192.168.0.2
192.168.0.200
So you have to make your own custom comparer like the below example.