从数据库返回多行

时间:2012-04-17 13:10:29

标签: c# arrays web-services

我在Web服务中使用以下方法返回一组数据 -

int T = 0;
res.rows = new users[1];
        int cnt = 0;

        while (reader.Read())
        {

            if (T == 0)
            {

                res.rows[T] = new users();

                res.rows[T].age = (String)reader["age"];
                res.rows[T].height = (String)reader["height"];

                T = T + 1;

            }
            cnt = cnt + 1;               
        }

        return res;

我目前设计此项以返回一行数据,在此设置res.rows = new users[1];然后j==0然后返回第一行数据。

我的问题是如何修改它以恢复多行/所有数据行? 提前谢谢。

2 个答案:

答案 0 :(得分:1)

public class User
{
    private string m_Age;
    private string m_Height;

    public User() { }

    public string Age
    {
        get { return m_Age; }
        set { m_Age = value; }
    }

    public string Height
    {
        get { return m_Height; }
        set { m_Height = value; }
    }

}

var rows = new List<User>();
while (reader.Read())
{

     var row = new User();
     row.Age = reader["age"];
     row.Height = reader["height"];
     rows.Add(row);
}

res.rows = rows; //if the res.rows property is an array then you can change this line to res.rows = rows.ToArray();

return res;

答案 1 :(得分:0)

尝试在代码中保持最小的更改,看起来像这样,

int T = 0;
res.rows = new List<User>();
    int cnt = 0;

    while (reader.Read())
    {

        //if (T == 0)
        {
            User u =new users();
            res.rows.Add(u);

            res.rows[T].age = (String)reader["age"];
            res.rows[T].height = (String)reader["height"];

            T = T + 1;

        }
        cnt = cnt + 1;               
    }

    return res;