"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

April 16, 2012

Tool Developer Notes - Part VIII

[Previous Post in Series - Tool Developer Notes Part VII]

Next Post is related to parsing tab delimited flat file and aggregate data from selected columns
Input format listed below


Expected output is


Steps for solving the problem
  • Parse a text file, aggregate selected column data and show aggregated results
  • Implemented using hashtables in C#
  • Update the values if key already exists for them
C# Example code. Please add necessary namespace to run this program, reusable method and example code listed below

using System;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Collections;

Code Snippet
public static string parsefiledata()
{
    char[] delimiterChars = { ' ', ',', '.', ':', '\t' };
    Hashtable AggregatedValues = new Hashtable();
    try
    {
        //Open Text File
        using (StreamReader sr = File.OpenText("E:\\sample.txt"))
        {
            string line;
            TextWriter tw = null;
            int newval = 0;
            while ((line = sr.ReadLine()) != null)
            {
                //Split it based on tab delimited spaces
                string[] Attributes = line.Split(delimiterChars);
                //Verify if Key Already Exists
                if (AggregatedValues.ContainsKey(Attributes[1]))
                {
                    newval = Convert.ToInt32(AggregatedValues[Attributes[1]]);
                    newval = Convert.ToInt32(Attributes[3]) + newval;
                    AggregatedValues[Attributes[1]] = newval.ToString();
                }
                //Add new Key if it does not exist
                else
                {
                    AggregatedValues.Add(Attributes[1], Convert.ToInt32(Attributes[3]));
                }
            }
        }
       
        foreach (string key in AggregatedValues.Keys)
        {
            Console.WriteLine(String.Format("{0}: {1}", key, AggregatedValues[key]));

        }
        Console.ReadKey();
        return "0";
    }
    catch (Exception ex)
    {
        return "-1";
    }

}

Console window output...

Happy learning!!!

No comments: