1

I have a list of valid IP's as a

List<string> IP = new List<string>()

For instance I could have:

192.168.1.54

192.168.1.95

192.168.1.22

192.168.1.26

192.168.1.4

192.168.1.11

192.168.1.103

How can I sort this list so it will appear sorted by last numerical value? (All the IP's will be within the same subnet so the first three octets won't matter)

192.168.1.4

192.168.1.11

192.168.1.22

192.168.1.26

192.168.1.54

192.168.1.95

192.168.1.103

Any ideas?

user3296337
  • 107
  • 10

1 Answers1

1

It works for List of strings too, just tested it, try this yourself:

List<string> unsortedIps = new List<string>();
        unsortedIps.Add("192.168.1.103");
        unsortedIps.Add("192.168.1.95");
        unsortedIps.Add("192.168.1.4");
        unsortedIps.Add("10.152.16.23");
        unsortedIps.Add("192.168.1.1");

        var sortedIps = unsortedIps
            .Select(Version.Parse)
            .OrderBy(arg => arg)
            .Select(arg => arg.ToString())
            .ToList();
kelsier
  • 4,050
  • 5
  • 34
  • 49
  • System.Collections.Generic.List does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference?) – user3296337 Mar 13 '14 at 08:31
  • I don't get that error, maybe version problems. Then try `var sortedIps = unsortedIps.ToArray().Select(Version.Parse).OrderBy(arg => arg).Select(arg => arg.ToString()).ToList();` – kelsier Mar 13 '14 at 08:35
  • Ahh just added using reference to System.Linq - it works now. Thanks a lot for your time – user3296337 Mar 13 '14 at 08:37