Linq/Lambda OrderBy Delegate for List of IP Addresses

前端 未结 6 679
粉色の甜心
粉色の甜心 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:12

    You could split this into 4 integer values, and sort by each in turn:

     var results = ips
           .Select(s => string.Split('.').Select(str => int.Parse(str)).ToArray() )
           .OrderBy(intArray => intArray[0])
           .ThenBy(intArray => intArray[1])
           .ThenBy(intArray => intArray[2])
           .ThenBy(intArray => intArray[3])
           .Select(intArray => string.Join(".", intArray) );
    

提交回复
热议问题