Thursday, April 25, 2013

Converting Csv to DataTable

Steps:
1. First, by using the File class static method ReadAllLines(path), read all the lines from the csv file  to the string array.
2. In the resulting array, first element contains the column names. using the first line, we should create the Data table columns.
3. Other than the first element, all other elements contains the row's data. Using the same we can create the data table rows.

Output

Creating Csv file from DataTable in C#

Steps:
1. Create a DataTable Schema.
2. Fill the created table with some sample data.
3. Create a StringBuilder, by appending all the data, (using comma delimiter)
    a) Create one new line with data table columns.
    b) Create one line for each data table row.
4. Save the StringBuilder to Csv file, using FileStream.

Friday, April 19, 2013

Excel Load To DataTable using OleDb in C#

Here we will try to load Excel sheet  data into the datatable using Jet engine.
First, We need to  Download and install the AccessDatabaseEngine exe from the microsoft web site.

Complete Source Code.

Friday, March 15, 2013

Split the List of objects into Batches using LINQ

There may be certain situations, When we have a number of objects in the list, but we need to split the objects into batches by batch size.

To Do that we can use LINQ, Skip and Take static methods.
Skip : Bypasses a specified number of elements in a sequence and then returns the remaining elements.
Take : Returns a specified number of contiguous elements from the start of a sequence.

Using both these static methods, we can split the list into multiple lists based on the batch size.

While writing the source code, my main intention is to just show how to split the list into batch sizes. So didn't bother about the validations, and other things. Kindly ignore those things.
  1.  First of all creating a Student Class. Which is a template to create the Student objects. ( We can use anonymous types also).
  2.  Then writing a method to create a list of objects for student class. I have just given some random data,  and creating some 23 objects.
  3.  Then writing a method to split the passed list of objects into batches, based on the passed batch size.
  4.  At last calling all the methods from the Main method.
Here i am giving the full source code.
Output: