如何获取字符串列表的两个索引中的值并将它们分配给两个字符串变量C#

时间:2016-06-29 04:51:24

标签: c# sql

我实现了一种方法来返回从查询生成的结果集并将其分配给字符串列表。我已设置将id(id是主键)和所选db表行的名称分配给字符串列表中的索引0和1。其代码如下,

    public List<string>[] getTrafficLevel()
    {
        string query = "select * from traffictimeinfo where startTime<time(now()) and endTime>time(now());";
        List<string>[] list = new List<string>[2];
        list[0] = new List<string>();
        list[1] = new List<string>();

        if (this.openConnection() == true)
        {
            MySqlCommand cmd = new MySqlCommand(query, connection);
            MySqlDataReader dataReader = cmd.ExecuteReader();

            while (dataReader.Read())
            {
                list[0].Add(dataReader["timeslotid"] + "");
                list[1].Add(dataReader["timeslotname"] + "");
            }
            dataReader.Close();
            this.closeConnection();
            return list;
        }
        else
        {
            return list;
        }
    }

我想知道的是如何将两个索引中的这个值分配到两个字符串变量中。

我尝试的方法如下,是否有人知道如何实现这一点..提前感谢..

    public void predictLevel(List<String>resList)
    {
        string trafficTime, trafficLevel;
        List<string>[]ansList = getTrafficLevel();
        ansList[0] = # want to assign the string value into trafficTime string variable
        ansList[1].ToString = # want to assign the string value into trafficLevel string variable
    }

1 个答案:

答案 0 :(得分:0)

您是否考虑过使用元组列表?

public List<Tuple<string,string>> getTrafficLevel()
{
    string query = "select * from traffictimeinfo where startTime<time(now()) and endTime>time(now());";
    List<Tuple<string,string>> list = new List<Tuple<string,string>>();

    if (this.openConnection() == true)
    {
        MySqlCommand cmd = new MySqlCommand(query, connection);
        MySqlDataReader dataReader = cmd.ExecuteReader();

        while (dataReader.Read())
        {
            list.Add(new Tuple<string,string>(dataReader["timeslotid"] + "", dataReader["timeslotname"] + ""));
        }
        dataReader.Close();
        this.closeConnection();
        return list;
    }
    else
    {
        return list;
    }
}

您的predictLevel方法将是 -

public void predictLevel(List<String>resList)
{
    string trafficTime, trafficLevel;
    List<Tuple<string,string>> ansList = getTrafficLevel();
    trafficTime = ansList[0].Item1;
    trafficLevel = ansList[0].Item2;
}