Convert datatable into an arraylist


This article shows how to convert a datatable into an arraylist. Suppose we have a DataTable and we want to copy the data from a particular datatable's specific column to ArrayList, then do as follows.

First, we construct the DataTable and next, we convert the particular DataTable's column values to Arraylist.

namespace CollectionsWebProject
{
    public partial class _Default : System.Web.UI.Page
    {
        string connectionString = "Data Source=LocalHost; 
        Initial CataLog=ERPFinAccounting; 
        User ID=kris; Password=XXX";
        protected void Page_Load(object sender, EventArgs e)
        {
		  ArrayList myArrayList = ConvertDataTableToArrayList();
          string str = string.Empty;
          foreach (string name in myArrayList)
          {
            str += name + "\n";
          }
        }


The below code creates a simple datatable of two columns: AccCode and AccName and adds two rows to the datatable.

 public ArrayList ConvertDataTableToArrayList()
        {   DataTable dtAccounts = new DataTable();
            DataColumn dataCol1 = new DataColumn("AccCode");
            DataColumn dataCol2 = new DataColumn("AccName");
            dtAccounts.Columns.Add(dataCol1);
            dtAccounts.Columns.Add(dataCol2);
            dtAccounts.Rows.Add("A001", "Capital Account");
            dtAccounts.Rows.Add("A002", "Expense Account");
         }


The below code creates an ArrayList. Uses two for loops - one for..loop iterates through each row of the datatable and another loop iterates each column of the selected row.

Adds the column values to the ArrayList. Before adding the column values, we need cast it to a string type by using ToString() method and assign them to arraylist.



 ArrayList myArrayList = new ArrayList();
    for (int i = 0; i <= dtAccounts.Rows.Count - 1; i++)
    {
      for (int j = 0; j <= dtAccounts.Columns.Count - 1; j++)
      {
           myArrayList.Add(dtAccounts.Rows[i][j].ToString());
      }
    }
    return myArrayList;
}


Authorship
By Bharati Karedla