List<string>排序问题
现有一个需求,需要对List<string>里面的Ip进行排序,
例如,集合是这样的:
List<string> IpList = new List<string>() {
"172.16.88.220"
+"222.73.29.77"
+"192.168.1.8"
+"172.16.88.2"
+"192.168.1.7"
+"172.16.88.10"
+"172.16.88.3"
+"172.16.88.8"
+"172.16.88.225"
+"172.16.88.100"
+"221.130.187.180"
+"221.130.187.181"
+"222.73.55.168"
+"172.16.88.7"
+"222.73.29.79"
+"172.16.88.200"
+"172.16.88.125"
+"192.168.1.1"
+"222.73.55.250"
+"115.236.102.216"
+"172.17.22.161"
+"222.73.29.135"
+"222.73.29.136"
+"172.17.22.162"
+"172.16.88.9"
+"115.238.26.184"
+"115.238.26.185"
+"115.238.26.186"
};
最后想要的顺序是:
115.238.26.184
115.238.26.185
115.238.26.186
115.236.102.216
172.16.88.2
172.16.88.3
172......
192.168.1.1
192.168.1.7
192....
222.73.29.77
222...
请问大家这个如何实现?
,"172.17.22.161"
,"222.73.29.135"
,"222.73.29.136"
,"172.17.22.162"
,"172.16.88.9"
,"115.238.26.184"
,"115.238.26.185"
,"115.238.26.186"
,"115.238.102.216"
};
IpList.Sort((s1, s2) =>
{
string[] array1 = s1.Split('.');
string[] array2 = s2.Split('.');
int index = 0;
bool equal = true;
while (equal && index < 4)
{
equal = array1[index] == array2[index];
index++;
}
return int.Parse(array1[index - 1]).CompareTo(int.Parse(array2[index - 1]));
});
foreach (string ip in IpList)
Console.WriteLine(ip);
------解决方案--------------------
OJ的方法是可以的,在LINQ里同样也可以实现:
,"192.168.1.8"
,"172.16.88.2"
,"192.168.1.7"
,"172.16.88.10"
,"172.16.88.3"
,"172.16.88.8"
,"172.16.88.225"
,"172.16.88.100"
,"221.130.187.180"
,"221.130.187.181"
,"222.73.55.168"
,"172.16.88.7"
,"222.73.29.79"
,"172.16.88.200"
,"172.16.88.125"
,"192.168.1.1"
,"222.73.55.250"
,"115.236.102.216"
,"172.17.22.161"
,"222.73.29.135"
,"222.73.29.136"
,"172.17.22.162"
,"172.16.88.9"
,"115.238.26.184"
,"115.238.26.185"
,"115.238.26.186"};
var result = from x in IpList
let 补齐字符串 = string.Join(".", x.Split('.').Select(y => string.Format("{0:C3}", y)).ToArray())
orderby 补齐字符串
select x;
foreach (var x in result)
Console.WriteLine(x);
Console.ReadKey();
}
}
}