A blog about SQL Server, SSIS, C# and whatever else I happen to be dealing with in my professional life.

Find ramblings

Thursday, May 20, 2010

PPrint for DataSet

I've make no bones about the coolness that is python and one of the methods available in there is pretty print (pprint). In my current project, I'm working with datasets and as much fun as it is to click through the locals window to examine the object or to try and catch the magnifying glass handle, I wanted something that would enumerate all the elements in a dataset and dump it to text. Call it a poorman's persistence mechanism. Thus, PPrint for datasets was born


/// <summary>
/// Pretty print a dataset
/// </summary>
/// <param name="ds">dataset that should be rendered to console</param>
public static void PPrint(System.Data.DataSet ds)
{
    System.Data.DataTable dt = null;
    if (ds == null)
    {
        Console.WriteLine("Dataset is null, n00b");
        return;
    }

    for (int tableIndex = 0; tableIndex < ds.Tables.Count; tableIndex++)
    {
        dt = ds.Tables[tableIndex];

        // Determine header
        // Console.WriteLine(dt.Namespace);
        Console.WriteLine("==========================================");
        Console.WriteLine(dt.TableName);
        Console.WriteLine("==========================================");

        foreach (System.Data.DataColumn dc in dt.Columns)
        {
            System.Console.Write(string.Format("{0}\t", dc.ColumnName));
        }

        Console.WriteLine();

        foreach (System.Data.DataRow row in dt.Rows)
        {
            for (int columnIndex = 0; columnIndex < dt.Columns.Count; columnIndex++)
            {
                Console.Write(string.Format("{0}\t", row[columnIndex]));
            }

            Console.Write("\n");
        }

        Console.WriteLine("{0} rows in table", dt.Rows.Count);
        Console.WriteLine("\n\n");
    }
}

TODO: sample input and output

No comments: