Thursday, 7 July 2011

Custom Functions for Datatable


Hi friends, more of the time when we need to shuffle the records or getting top n rows while retrieving the data from database. We often use database function in our stored procedures.

But what if once you have fetched the data in datatable and now you have requirement to perform these two task with you tabular data. The solution that comes in mind is, create a custom function and get the desired result from datatable. 

Here is the some custom function that can be useful while dealing with datatables.

1. Shuffling the DataTable

/// <summary>
/// Randomizes the order of the rows in a DataTable by pulling out a single row and moving it to the end for
/// shuffleIterations iterations.
/// </summary>
/// <param name="inputTable"></param>
/// <param name="shuffleIterations"></param>
/// <returns></returns>
public static DataTable shuffleTable(DataTable inputTable, int shuffleIterations)
{
    int index;
    System.Random rnd = new Random();
    // Remove and throw to the end random rows until we have done so n*3 times (shuffles the dataset)
    for (int i = 0; i < shuffleIterations; i++)
    {
        index = rnd.Next(0, inputTable.Rows.Count - 1);
        inputTable.Rows.Add(inputTable.Rows[index].ItemArray);
        inputTable.Rows.RemoveAt(index);
    }
    return inputTable;
}

2. Getting Top n rows from DataTable

/// <summary>
/// Return Top n rows from a datatable
/// </summary>
/// <param name="dt">Source DataTable that is to be filetered</param>
/// <param name="n">No. of records you need in output datatable</param>
/// <returns>DataTable Contains the Resuling n rows</returns>
public DataTable getTop(DataTable dt, int n)
{
    DataTable outputTable = dt.Clone();
    for (int i = 0; i < n; i++)
        outputTable.ImportRow(dt.Rows[i]);
    return outputTable;
}

Well these custom function can be very useful to you guys so I am sharing it with you.