【发布时间】:2017-08-02 18:54:01
【问题描述】:
我有一种方法可以从数据库中计算每个月的总金额,如图所示。
public static List<Sale> ChartMonthlySalePerYear()
{
using (SQLiteConnection con = new SQLiteConnection(Connection.DatabaseLocationString))
{
SQLiteCommand cmd = null;
string query = String.Format("SELECT strftime('%m', SaleDate) AS month, SUM(AmountPaid) AS sum_amountpaid FROM {0} WHERE strftime('%Y', SaleDate) = @1 GROUP BY strftime('%m', SaleDate) ", Sale.TABLE_NAME);
cmd = new SQLiteCommand(query, con);
cmd.Parameters.Add(new SQLiteParameter("@1", Properties.Settings.Default.ChartYearlyDisplay));
con.Open();
SQLiteDataReader reader = cmd.ExecuteReader();
var list = new List<Sale>();
while (reader.Read())
{
Sale value = new Sale()
{
Months = reader["month"].ToString(),
SUMAmountPaid = Convert.ToDecimal(reader["sum_amountpaid"])
};
list.Add(value);
}
con.Close();
return list;
}
}
它会按月返回一个这样的列表,
- 01 20000.00(例如一月)
- 02 13000.00(例如二月)
- 03 10000.00(例如三月)
- 04 10000.00(例如四月)
- 05 10000.00(例如五月)
- 06 20000.00(例如六月)
- 07 15000.00(例如 7 月) 但是其他月份还没有销售。
这就是使用方法的地方。
List<Sale> sum = SaleViewModel.ChartMonthlySalePerYear();
Jan = sum[0].SUMAmountPaid;
Feb = sum[1].SUMAmountPaid;
Mar = sum[2].SUMAmountPaid;
Apr = sum[3].SUMAmountPaid;
May = sum[4].SUMAmountPaid;
Jun = sum[5].SUMAmountPaid;
Jul = sum[6].SUMAmountPaid;
//For Ausgust
if (sum[7] != null)
Aug = 0;
else
Aug = sum[7].SUMAmountPaid;
//For September
if (sum[7] != null)
Sep = 0;
else
Sep = sum[7].SUMAmountPaid;
我现在的挑战是,8 月和 9 月没有价值,我想先检查一下,然后再给它一个默认值,但它会抛出异常。 Index was out of range. Must be non-negative and less than the size of the collection. 8 月和 9 月。
提前致谢。
【问题讨论】:
-
问题是什么,你提出的 if 条件不起作用?
-
是的............
-
你不需要在那里调用
Close。你的using语句应该处理实例并关闭它。另外,您对这份清单的处理不当。您根本不应该在这里使用 index 或 ElementAt,因为您有一个应该用于此目的的Months属性。 -
好的,非常感谢您提供的信息。 @BrettCaswell