我正在尝试添加 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())
循环中向列表中添加任何内容。 GetRecords
和 GetRecords2
均缺少 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/