如何将对象的属性转换为列表元素

时间:2019-02-12 12:31:47

标签: c#

我正在尝试从数据库中获取所有数据,并使用ajax和存储过程将其显示在表中。

public List<string> ShowDetailsFromDB()
{
    using (adoHelper = new AdoHelper(connectionString))
    {
        List<string> users = new List<string>();  
        string procedureName = "GetDetails";
        SqlDataReader dataReader = adoHelper.ExecuteDataReaderByProcedure(procedureName);
        while (dataReader.Read())
        {
            User user = new User();
            user.userId = dataReader[1] as string;
            user.password = dataReader[2] as string;
            user.userName = dataReader[3] as string;
            user.address = dataReader[4] as string;
            user.email = dataReader[5] as string;
            user.phone = dataReader[6] as string;

            //here I want to assign each object property as list element

        }
        return users;
    }
}

2 个答案:

答案 0 :(得分:1)

以下是从rd实例的属性生成字符串列表的两种方法。

     id st  rd cm  new_id
0  4735  a  CU  m  4567
1    46  a  SU  m  1234
2  2345  d  NU  m  2367
3  8768  e  NU  m  5687
4   807  f   W  m  8796
5  7896  a  CU  m  7865

上面的代码可以很简单地在您的代码中使用,尽管您必须返回一个字符串数组列表以获取所有用户的所有属性。

User

答案 1 :(得分:0)

您可以使用“用户列表”轻松完成此操作。

public class User
{
    public string userId { get; set; }
}
public List<User> ShowDetailsFromDB()
{
    using (adoHelper = new AdoHelper(connectionString))
    {
        List<User> users = new List<User>();
        string procedureName = "GetDetails";
        SqlDataReader dataReader = adoHelper.ExecuteDataReaderByProcedure(procedureName);
        while (dataReader.Read())
        {
            User user = new User
            {
                userId = dataReader[1] as string
            };

            users.Add(user);
            //here I want to assign each object property as list element

        }
        return users;
    }
}

请告诉我是否可行