你好我是新手C#编程,我在C#函数中返回数组类型时遇到问题。它来自查询数据库的返回值(下面的代码):
//determine list of lesson
private string fillTreeLesson(string course_id)
{
string connectionString = "server=localhost; database=moodle; user=root; password=";
using (MySqlConnection con = new MySqlConnection(connectionString))
{
try
{
con.Open();
MySqlCommand cmnd = con.CreateCommand();
string sql = "select name from lesson where course like '%"+course_id+"%'";
cmnd.CommandText = sql;
MySqlDataReader reader = cmnd.ExecuteReader();
while (reader.Read())
{
lesson_name = reader.GetString("name");
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return lesson_name;
}
所以我的问题是:
如何使用上述功能,并按返回值索引调用。如果我会这样调用(fillTreeLesson是我将使用的函数的名称):
treeOutline.Nodes [counter_node] .Nodes.Add(fillTreeLesson(COURSE_NAME));
感谢关注
答案 0 :(得分:1)
您可以使用以下列表轻松完成:
public List<string> FillTreeLesson(string course_id)
{
List<string> returnList = new List<string>();
try
{
con.Open();
MySqlCommand cmnd = con.CreateCommand();
string sql = "select name from lesson where course like '%"+course_id+"%'";
cmnd.CommandText = sql;
MySqlDataReader reader = cmnd.ExecuteReader();
while (reader.Read())
{
lesson_name = reader.GetString("name");
returnList.Add(lesson_name);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return returnList;
}
为了调用此功能,
首先使列表包含您的结果:
List<string> namesList = new List<string>();
然后调用该函数并将其输出放在 namesList 中 创建:
namesList = FillTreeLesson("CS-502");
之后,您可以轻松地逐个使用这些字符串 foreach 循环:
foreach(string currentName in namesList)
{
//Whatever you want to do with currentName
}
OR
你可以使用for循环(如果你想在某些中使用它们,则优选 订单使用其索引值或必须稍后更改其值 上)
for(int i=0; i<namesList.Count; i++)
{
//Your code. You should access given element as namesList[i]
}