You can refactor that method into something like this:
private IList<string> Load(string tableName, string columnName)
{
var result = new List<string>();
cn.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand(string.Format("select* from {0}", tableName), cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
result.Add(reader[columnName].ToString());
}
cn.Close();
return result;
}
Your code sample will be:
var milkItems = Load("Milk", "Product");
var classicItems = Load("Classics", "..."); //Enter the column here.
Edit:
You might want something a little more specific (eg. storing a List<SomeObject>
instead of just List<string>
). Let's suppose you sometimes you want to return a list of Person
, and also you want to read a list of Building
. Then you can write something like this (not compiled & tested):
private IList<T> Load<T>(string tableName, Func<OleDbDataReader, T> selector)
{
IList<T> result = new List<T>();
cn.Open();
OleDbDataReader reader = null;
OleDbCommand cmd = new OleDbCommand(string.Format("select* from {0}", tableName), cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
result.Add(selector(reader));
}
cn.Close();
return result;
}
and you can call it like:
Func<OleDbDataReader, Person> selector = x => new Person { Name = x["Person"].ToString() };
Load("People", selector);