如何检查List <T>索引是否为空

MIc*_*vid 0 c# indexing list

我有一个方法,可以从db计算每个月的总金额,如图所示.

 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;

        }
    }
Run Code Online (Sandbox Code Playgroud)

它按月返回这样的List,

  • 01 20000.00(例如1月)
  • 02 13000.00(例如二月)
  • 03 10000.00(例如3月)
  • 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;
Run Code Online (Sandbox Code Playgroud)

我现在的挑战是,8月和9月没有价值,我想在我给它一个默认值之前先检查一下,但它抛出一个例外. Index was out of range. Must be non-negative and less than the size of the collection. 8月和9月.提前致谢.

Tim*_*Tim 6

您希望在访问该索引之前检查索引是否小于或等于列表的长度,以避免索引超出范围异常:

if (sum.Count <= 7) 
   Aug = 0;
else
   Aug = sum[7].SUMAmountPaid;
Run Code Online (Sandbox Code Playgroud)

但是,如果您的数据存在漏洞,这将无法正常运行.如果数据中有漏洞,List的索引将不会与月份匹配.如果是这种情况,请考虑使用Dictionary<int, Sale>():

var salesByMonth = new Dictionary<int, Sale>();
while (reader.Read())
{
    Sale value = new Sale()
    {
        Months = reader["month"].ToString(),
        SUMAmountPaid = Convert.ToDecimal(reader["sum_amountpaid"])
    };
    salesByMonth.Add(int.Parse(value.Months), value);
}
Run Code Online (Sandbox Code Playgroud)

Sale value;
if (salesByMonth.TryGetValue(1, out value))
   Jan = value.SUMAmountPaid;
else
   Jan = 0;

if (salesByMonth.TryGetValue(2, out value))
   Feb = value.SUMAmountPaid;
else
   Feb = 0;
Run Code Online (Sandbox Code Playgroud)