Home > database >  select IP and index from the list<Uint> based on String of the IP c#
select IP and index from the list<Uint> based on String of the IP c#

Time:01-04

I have a list include Uint of ips . for example 168470721 for "192.169.10.10". A string of ip is given and we have to check if its IP or IPs are in the list or not. Then return the ips and his indexes as dictionary.

          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"

and the function for find ips and 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;
        }

This method is slow for large data. Can we write with a LinQ?

CodePudding user response:

Instead of converting the list items to an array of bytes and then converting to a string and comparing the string, It is better to convert the input IP to uint and use linq. (uint comparison is faster than string comparison. Also, converting the entire list to a string degrades performance)

    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);
    }
  • Related