使用来自返回列表的变量<>;方法

本文关键字:lt gt 方法 变量 返回 列表 | 更新日期: 2023-09-27 18:29:26

希望这次是一个非常简单的问题。我在数据库连接器类中有一个Select方法,如下所示;

  public List <string> [] Select(string mQuery)
{
    //Create a list to store the result
    List<string>[] datalist = new List<string>[1];
    datalist[0] = new List<string>();

    //Open connection
    if (this.OpenConnection() == true)
    {
        //Create Command
        MySqlCommand cmd = new MySqlCommand(mQuery, mConnection);
        //Create a data reader and Execute the command
        MySqlDataReader dataReader = cmd.ExecuteReader();
        //Read the data and store them in the list
        while (dataReader.Read())
        {
            datalist[0].Add(dataReader["id"] + "");
        }
        //close Data Reader
        dataReader.Close();
        //close Connection
        this.CloseConnection();
        //return list to be displayed
        return datalist;
    }
    else
    {
        return datalist;
    }
}

当我想访问"数据列表"时,我假设我这样称呼它;

      results = mDB.Select(mQuery);

但是因为返回的值是一个列表,我是否需要将这个变量分配给一个新的列表,比如so;?

 List<string>[] results = new List<string>[1];
                       results[0] = new List<string>();
                       results = mDB.Select(mQuery);
                       string result = results[0].ToString();
                       MessageBox.Show(result);

此消息框只生成"System.Collections.Generic.List1(System.String)"

你知道我做错什么的逻辑吗?

使用来自返回列表的变量<>;方法

是否尝试不将列表包装在数组中?

 List<string> results = new List<string>();
 results = mDB.Select(mQuery);
 string result = results[0].ToString();
 MessageBox.Show(result);

无论哪种方式,问题都是您试图显示一个列表,默认情况下,该列表只返回其类型。您应该显示列表的成员,而不是列表本身。

如果你想做的是以逗号分隔的方式显示列表的内容,你可以这样做:

MessageBox.Show(string.Join(",", list));

得到"System.Collections.Generic.List1(System.String)"的原因是ListToString只返回其类型的字符串表示。

此外,正如其他人所指出的,您应该丢失数组。你想要的是:

public List<string> Select(string mQuery)
{
    //...
}
List<string> list = mDB.Select(mQuery);
MessageBox.Show(string.Join(",", list));