今天群里有人在问如何用sql对IP地址进行排序,首先想到的是把IP切割,但是用substring太麻烦了,于是就百度到了T-SQL拆分IP地址 这边文章,PARSENAME真是个好东西,
用起来真是太丝滑了,然后就结束了
与此同时,还用C#代码写了个扩展方法也实现了对IP字段的排序:
1 public static ICollection<string> Order(this ICollection<string> ips, bool asc = true) 2 { 3 if(ips==null) 4 throw new ArgumentNullException(nameof(ips)); 5 foreach (var ip in ips) 6 { 7 IPAddress tmp; 8 if (!IPAddress.TryParse(ip, out tmp)) 9 { 10 throw new Exception("Illegal IPAdress data."); 11 } 12 } 13 Func<string, int, int> func = (s, i) => 14 { 15 var tmp = s.Split('.'); 16 return int.Parse(tmp[i]); 17 }; 18 if (asc) 19 { 20 return ips.OrderBy(m => func(m, 0)) 21 .OrderBy(m => func(m, 1)) 22 .OrderBy(m => func(m, 2)) 23 .OrderBy(m => func(m, 3)) 24 .ToList(); 25 } 26 return ips.OrderByDescending(m => func(m, 3)) 27 .OrderByDescending(m => func(m, 2)) 28 .OrderByDescending(m => func(m, 1)) 29 .OrderByDescending(m => func(m, 0)) 30 .ToList(); 31 }