.net 根据IP c#的字符串从列表中选择IP和索引< Uint>

6l7fqoea  于 2023-01-06  发布在  .NET
关注(0)|答案(1)|浏览(105)

我有一个list include Uint of ips。例如168470721 for "192.169.10.10"。一个ip字符串被给定,我们必须检查它的IP或IP是否在列表中。然后返回ip和他的索引作为字典。

public List<uint> IPs = new List<uint>();

            IPs.Add(168470721); //index = 0;  ip="193.168.10.10"
            IPs.Add(185247937); //index = 1;  ip="193.168.10.11"
            IPs.Add(202025153); //index = 2;  ip="193.168.10.12"
            IPs.Add(168470721); //index = 3;  ip="193.168.10.10"

以及用于查找ips和index的函数:

public Dictionary<int, uint> findIPS(string ip)
        {
           Dictionary<int,uint> map = new Dictionary<int,uint>();
            for (int i = 0; i < IPs.Count; i++)
            {
                byte[] Byte_IP2 = BitConverter.GetBytes(IPs[i]);

                string ipOfBytes = Byte_IP2[0].ToString() + "." + Byte_IP2[1].ToString()
                            + "." + Byte_IP2[2].ToString() + "." + Byte_IP2[3].ToString();

                if (ipOfBytes == ip)
                    map.Add(i, IPs[i]);
            }
            return map;
        }

这种方法对于大数据来说速度很慢。我们可以用LinQ写吗?

w6mmgewl

w6mmgewl1#

与其转换list items to an array of bytes,然后转换converting to a stringcomparing the string,不如转换input IP to uint并使用linq。(uint比较与faster than string比较相同。而且,将整个列表转换为字符串会降低性能)

public Dictionary<int, uint> findIPS2(string ip)
    {    
        var uintOfIP = IpAddressToUint(ip);
        return IPs.Select((s, index) => new { index,s }).Where((s, index)=>s.s == uintOfIP)
            .ToDictionary(x => x.index, x => x.s);        
    }

    public uint IpAddressToUint(string ipAddress)
    {
        var address = IPAddress.Parse(ipAddress);
        byte[] bytes = address.GetAddressBytes();
        return BitConverter.ToUInt32(bytes, 0);
    }

相关问题