0

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));
        }
 }
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
newbie
  • 273
  • 2
  • 4
  • 13
  • OK. Now what is your question? – Sami Kuhmonen Nov 05 '16 at 12:47
  • yes, its is necessary 118.168.5.1 1.198.6.7. compare with this data – Vivek Nuna Nov 05 '16 at 12:48
  • `.OprderBy(p => p)` is the correct command and it doesn't require any custom comparer. – Cristian Szpisjak Nov 05 '16 at 12:49
  • Use `IPAddress.Parse(x).ToInteger()` in the anonymous function. – Javier Nov 05 '16 at 12:55
  • @newbie could you explain why you are actually are comparing, what is the expected result ? *(Is it necessary to write a custom comparer)* ... depends what, how, why you want to compare ... – Jim Nov 05 '16 at 13:01
  • @Jim Actually I want my users to search between two ranges of IPs in my application. something like `between` in TSQL – newbie Nov 05 '16 at 13:04
  • @newbie edit your question with necessary details. It will improve the chance to get a decent answer. *(What do I want it to do, what I am doing, what it does, what I expect it should have done)* – Jim Nov 05 '16 at 13:08

1 Answers1

0

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

Community
  • 1
  • 1
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197