在c#中添加两个方法的列表

时间:2013-04-10 19:41:10

标签: c# list add

我正在尝试使用getRecords列表添加getRecords2列表。出于某些原因,在getRecords上,当我调用它时需要很长时间来处理和超时。

public static List<ListA> getRecords2(string id)
{
   List<ListA> listOfRecords = new List<ListA>();
   using (SqlConnection con = SqlConnect.GetDBConnection())
   {
      con.Open();
      SqlCommand cmd = con.CreateCommand();
      cmd.CommandText = "sp2";
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.Add(new SqlParameter("@id", id));

      SqlDataReader reader = cmd.ExecuteReader();

      while (reader.Read())
      {
         ListA listMember = new ListA();
         listMember.ID = (int)reader["ID"];
     listMember.Name = reader["FullName"].ToString().Trim();
      }
      con.Close();
    }
       return listOfRecords;
  }

  public static List<ListA> getRecords(string id)
  {
     List<ListA> listOfRecords = new List<ListA>();
     using (SqlConnection con = SqlConnect.GetDBConnection())
     {
        con.Open();
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandText = "sp1";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(new SqlParameter("@id", id));

        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
           ListA listMember = new ListA();
           listMember.ID = (int)reader["ID"];
           listMember.Name = reader["FullName"].ToString().Trim();
        }
        con.Close();
      }
      List<ListA> newlist = getRecords(id);
      foreach (ListA x in newlist) listOfRecords.Add(x);
      return listOfRecords;
   }

我在getRecords2中添加了getRecords列表。我做错了吗?

1 个答案:

答案 0 :(得分:7)

首先,您没有在while(reader.Read())循环中向列表中添加任何内容。 AddGetRecords上都缺少GetRecords2方法调用:

    while (reader.Read())
    {
        ListA listMember = new ListA();

        listMember.ID = (int)reader["ID"];
        listMember.Name = reader["FullName"].ToString().Trim();

        // you have to add this line:
        listOfRecords.Add(listMember);
    }

另一个问题是:你一遍又一遍地呼叫getRecords(id)

List<ListA> newlist = getRecords(id);
foreach (ListA x in newlist) listOfRecords.Add(x);

应该是:

List<ListA> newlist = getRecords2(id);
foreach (ListA x in newlist) listOfRecords.Add(x);

最后但并非最不重要:您不必致电con.Close(); - 当程序流退出using时,它会自动完成,作为Dispose方法的一部分。< / p>