c# - 从 C# 中的两种方法添加列表

标签 c# list add

我正在尝试添加 getRecords2 列表和 getRecords 列表。由于某种原因,在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 列表。我做错了吗?

最佳答案

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

    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(); - 当程序流退出 使用 block 时它会自动完成,因为Dispose 方法的一部分。

关于c# - 从 C# 中的两种方法添加列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15934936/

相关文章:

assembly - 如何仅使用 mov、add、sub、neg 限制 4 条指令中的 x=2a+3b?

javascript - 使用javascript将文本节点添加到SVG组但没有出现

c# - 将经典 ASP 转换为 ASP.NET C#

c# - Visual C# 找不到我的 Ionic Zip .dll 文件

python - 如何在运行时在Python数组中添加值?

c# - 我将什么传递到 List<Object>.Sort() 以按 Object.SomeInteger 对项目进行排序?

python - 如何使用 python 列表理解/字典将每一列打印为唯一变量

php - 如何通过检查当前函数名添加一个 "active"类

c# - 如何使用 C# 替换字符串中的多个单词?

c# - 让算法更高效