Search code examples
c#arraylistgeneric-collections

What is a more general way of creating an arraylist in C# like the one in the example?


Objective: Achieve a more general way of creating an arraylist.

Issue: I have to create multiple arraylists, each matched to a unique structure for the purpose of comparing and updating a table in Sql database. In the spirit of DRY I am trying to find a better way of creating each array. The code I am using is as follows

Sample Code:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Diagnostics;  
using System.Data;  
using System.Data.SqlClient;  
using System.Collections;  
using System.Configuration;  

public static void Users()
{
    String sql = "";

    try
    {

         conn.Open();

         sql = "SELECT" +
                   "database.dbo.table1.username," +
                   "database.dbo.table1.status"   +
               "FROM" +
                   "database.dbo.table1";
         SqlCommand cmd = new SqlCommand(sql, conn);

         SqlDataReader dr = cmd.ExecuteReader();

         while (dr.Read())
         {
              //structure below
              User structure_A = new User();

              structure_A.username = dr.GetValue(0).ToString();
              structure_A.status   = dr.GetValue(1).ToString();

              //added to arraylist
              arraylist_A.Add(structure_A);
          }

          dr.Close();
          conn.Close();
}

Note: More information can be provided as requested. Thank you in advance for any insight


Solution

  • One thing you can do is create a generic method that takes the parameters that differ. For example:

    public static ArrayList LoadInfo<T>(string sql, Func<SqlDataReader, T> getItem) where T: new
    {
        var list = new ArrayList();
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            list.Add(getItem(dr));
        }
        return list;
    }
    
    public static User LoadUser(SqlDataReader dr)
    {
        User structure_A = new User();
        structure_A.username = dr.GetValue(0).ToString();
        structure_A.status   = dr.GetValue(1).ToString();
        return User;
    }
    

    Now, to call it to load users, you just pass it the SQL query and the LoadUser method:

    string usersQuery = "SELECT ....";  // select users query
    ArrayList usersList = LoadInfo(usersQuery, LoadUser);
    

    And if you need to load a bunch of Fooby objects, you'd create the Fooby query and a LoadFooby method that can create and populate a Fooby from the data row.

    I'd suggest that you look into using List rather than ArrayList.