Tuesday, October 6, 2009

LINQ. Sample. Sort list of IP addresses

In file “list.txt” I have one-per-line list of IP addresses that I’d like to sort.
I understand that it’s possible to do in many different ways.
But I’d like to illustrate use of LINQ for this.



Function to calculate decimal presentation of IP address:
private Int64 Ip2Decimal(String ip)

{
    String[] d;
    Int64 iRes = -1;

    try {
        d = ip.Split('.');
        iRes = Int64.Parse(d[3]) + 256 * (Int64.Parse(d[2]) + 256 *
              (Int64.Parse(d[1]) + 256 * Int64.Parse(d[0])));
    }
    catch (Exception) {}
    return iRes;
}
Read unordered list and write the sorted one:
// file "list.txt" contains one-per-line IP address


StreamReader sr = new StreamReader("list.txt");
String txtIp = sr.ReadToEnd();
sr.Close();



// dictionary with key=IpAddress, value={decimal presentation}
Dictionary<String, Int64> listIP = new Dictionary<String, Int64>();
String[] arr = txtIp.Split(Environment.NewLine.ToCharArray());

foreach (String strIP in arr)
{
    if (strIP.Length > 0 && !listIP.ContainsKey(strIP))
    {
        listIP.Add(strIP, Ip2Decimal(strIP));
    }
}

var orderedIpList = from ip in listIP
                    orderby ip.Value
                    select ip.Key;

String[] orderedArr=orderedIpList.ToArray();
StreamWriter sw = new StreamWriter("orderedList.txt");
txtIp = String.Join(Environment.NewLine, orderedArr);
sw.Write(txtIp);
sw.Close();


     

No comments:

Post a Comment