I have 2 methods for getting data from the database (the data I get are both List
of tuples with double
s and datetimes in it). I would like to know if it is possible to use one method for both queries.
How can I make this code DRY? In my opinion I'm defining 2 methods which clearly does nearly the same. How can I improve this? I've read some about predicates and delegates but I'm not sure how to apply them here.
private IEnumerable<Tuple<double, DateTime>> GetCarHdopById(int id)
{
var tp = new List<Tuple<double, DateTime>>();
db.OpenConnection();
var result = db.QueryDatabaseById("SELECT avg(hdop),to_char(datetime, 'YYYY-MM-DD') as average_hdop FROM positions where unitid = :id group by to_char(datetime, 'YYYY-MM-DD');",id);
while (result.Read())
{
var avgHdopPerCar = Convert.ToDouble(result[0]);
var date = Convert.ToDateTime(result[1]);
tp.Add(new Tuple<double, DateTime>(avgHdopPerCar, date));
};
db.CloseConnection();
return tp;
}
private List<Tuple<double, DateTime>> GetCarHdopTotalCarsPerDay()
{
var tp = new List<Tuple<double, DateTime>>();
db.OpenConnection();
var result = db.QueryDatabase("SELECT avg(hdop),to_char(datetime, 'YYYY-MM-DD') as average_hdop FROM positions group by to_char(datetime, 'YYYY-MM-DD');");
while (result.Read())
{
var avgHdopPerCar = Convert.ToDouble(result[0]);
var date = Convert.ToDateTime(result[1]);
tp.Add(new Tuple<double, DateTime>(avgHdopPerCar, date));
};
db.CloseConnection();
return tp;
}
Query database method (I can probably overload this one):
public NpgsqlDataReader QueryDatabase(string query)
{
var command = new NpgsqlCommand(query, conn);
command.Connection = conn;
return command.ExecuteReader();
}
public NpgsqlDataReader QueryDatabaseById(string query, int parameters)
{
var command = new NpgsqlCommand(query, conn);
command.Parameters.Add("id",NpgsqlDbType.Integer);
command.Prepare();
command.Parameters[0].Value = parameters;
command.Connection = conn;
return command.ExecuteReader();
}