Linq/Lambda OrderBy Delegate for List of IP Addresses

前端 未结 6 663
粉色の甜心
粉色の甜心 2021-01-01 21:34

Given List ips = new List();

I need to sort the list of IP addresses in a logical order (i.e. \"192.168.0.2\" comes before \

6条回答
  •  天命终不由人
    2021-01-01 22:24

    You need to make a comparer: (Tested)

    class IPComparer : IComparer {
        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()) 
    

提交回复
热议问题