List的 Linq/Lambda OrderBy 委托IP 地址数
给定 List
我需要按逻辑顺序对 IP 地址列表进行排序(即“192.168.0.2”位于“192.168.0.100”之前)。
当前(正确地,按字母顺序)如果列表包含:
192.168.0.1
192.168.0.2
192.168.0.10
192.168.0.200
ips.OrderBy(p => p) 则返回:
192.168.0.1
192.168.0.10
192.168.0.2
192.168.0.200
Given List<string> ips = new List<string>();
I need to sort the list of IP addresses in a logical order (i.e. "192.168.0.2" comes before "192.168.0.100").
Currently (and correctly, alphabetically) if the list contains:
192.168.0.1
192.168.0.2
192.168.0.10
192.168.0.200
ips.OrderBy(p => p)
returns:
192.168.0.1
192.168.0.10
192.168.0.2
192.168.0.200
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您需要制作一个比较器:(已测试)
然后您可以编写
You need to make a comparer: (Tested)
You can then write
我会像这样为
System.Net.IPAddress
创建一个比较器,然后按以下步骤操作:
I would create a comparer for
System.Net.IPAddress
like soand then proceed as follows:
您可以将其拆分为 4 个整数值,然后按每个整数值依次排序:
You could split this into 4 integer values, and sort by each in turn:
这个非常优雅(如果您使用
TryParse
,并且可以防止失败):只要
addressBytes
数组只是 IP4 地址,它的长度就为 4。否则你应该考虑长度......This one is pretty elegant (and fail proof if you use
TryParse
):The
addressBytes
array will have length 4 as long as it is only IP4 addresses. Otherwise you should account for the length...我为 IPv6 编写了一个 IpComparer。 Howel 的变体不起作用。
这是比较器:
这是一个单元测试:
我希望这个解决方案是正确的。我不是 IPv6 方面的专家。
I wrote an IpComparer for IPv6. The variant from Howel doesn't work.
Here is the Comparer:
And here a unit test:
I hope this solution is correct. I'm not an expert in IPv6.
这是一个老问题,但我在查找 IP Comparer 时发现了这个问题。我想要一些也适用于 IPv6 的东西,所以一旦我得到它,我想我会将它添加到这里,以便下一个搜索它的人。就像 SLAks 的回答一样,我同意 IComparer 可能是最好的。
没什么特别的,但应该可以。
This is an old question but I was looking up IP Comparer's and it came up. I wanted something that worked for IPv6 as well though so once I got it I thought I'd add it here for the next person who does a search for it. Much like SLaks's answer, I agree that an IComparer is probably best.
Nothing fancy but it should work.