List <t>:只获得最后一个索引记录

时间:2015-12-29 14:15:59

标签: c# asp.net arrays asp.net-mvc kendo-ui

我有一个返回Kendo调度程序数据列表的方法。我的问题是,我可以从数据库获得39条独特的记录。

此处我还获得了39条记录,但所有记录都是最后一条索引记录数据

protected object GetData()
        {
            cal_details cal = new cal_details();
            List<cal_details> lst = new List<cal_details>();
            DataSet dSet = new DataSet();
            try
            {
                dSet = (DataSet) DAL.SC(1, 1, 0, 0, 0, "", "", "", 1, "tblCal");
                if (dSet.Tables["tblCal"].Rows.Count > 0)
                {
                    lst.Clear();
                    for (int i = 0; i <= dSet.Tables["tblCal"].Rows.Count - 1; i++)
                    {
                        cal.Description = "Test";
                        cal.isAllDay = true;
                        //cal.OwnerID = 2;
                        cal.Start = Convert.ToDateTime(dSet.Tables["tblCal"].Rows[i]["working_date"].ToString());
                        cal.End = Convert.ToDateTime(dSet.Tables["tblCal"].Rows[i]["working_date"].ToString());
                        cal.OwnerID = dSet.Tables["tblCal"].Rows[i]["date_cat"].ToString();
                        cal.TaskID =i;
                        cal.Title = "Test Title";
                        lst.Add(cal);   
                    }
                }
                return lst;
                }
            catch (Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage() { StatusCode = HttpStatusCode.NoContent, Content = new StringContent("There were some Errors") });`enter code here`
            }
        }

2 个答案:

答案 0 :(得分:2)

您正在使用相同的cal_details对象。您需要为每一行创建一个新对象。

移动此行:

cal_details cal = new cal_details();

for循环中,如下所示:

for (int i = 0; i <= dSet.Tables["tblCal"].Rows.Count - 1; i++)
{
    cal_details cal = new cal_details();
    //...
}

答案 1 :(得分:1)

您基本上创建了一个在循环中多次更改的对象,然后将其多次添加到列表中。它产生一个列表,其中所有元素都是同一条数据。

解决方案:

移动

cal_details cal = new cal_details();

进入循环

for (int i = 0; i <= dSet.Tables["tblCal"].Rows.Count - 1; i++)
{
   cal_details cal = new cal_details();
...