newbie
newbie

Reputation: 283

Using custom comparer for strings

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));
        }
 }

Upvotes: 0

Views: 659

Answers (1)

Vivek Nuna
Vivek Nuna

Reputation: 1

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.

https://stackoverflow.com/a/4785462/6527049

Upvotes: 0

Related Questions