简体   繁体   English

如何填写列表<String>使用 SqlDataAdapter?

[英]How to fill List<String> with SqlDataAdapter?

I am trying to fill List with SqlDataAdapter.我正在尝试用 SqlDataAdapter 填充列表。 But i am not able to do it.Is there any other method to fill List of string apart from Data Adapter.但是我做不到。除了数据适配器之外,还有其他方法可以填充字符串列表吗? Please help me out to solve this problem.Thanks in advance.请帮我解决这个问题。提前致谢。

This is my code:这是我的代码:

public List<String> JSONDataAll()
        {
            List<String> Users = new List<String>();
            con.Open();
            SqlCommand cmd = new SqlCommand("sp_sample_Proc", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(Users);
        }

Simplest way would be read your data through SqlDataReader and then fill your list iterating your resultset.最简单的方法是通过SqlDataReader读取您的数据,然后填充您的列表迭代您的结果集。 Like:喜欢:

public List<String> JSONDataAll()
{
    List<String> Users = new List<String>();
    using (SqlConnection con = new SqlConnection("connectionString"))
    {
        con.Open();
        using (SqlCommand cmd = new SqlCommand("sp_sample_Proc", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    Users.Add(reader.GetString(0)); //Specify column index 
                }
            }
        }
    }
    return Users;
}

In your current code you are trying to fill List<string> using DataAdapter .在您当前的代码中,您正在尝试使用DataAdapter填充List<string> You can't do that.你不能那样做。 Instead you can fill a DataTable and then get a List<string> like:相反,您可以填充一个DataTable ,然后获得一个List<string>例如:

DataTable dt = new DataTable();
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Users = dt.AsEnumerable()
    .Select(r => r.Field<string>("ColumnName"))
    .ToList();

But, You shouldn't do that .但是,你不应该那样做 It would result in multiple iterations, first for filling up the DataTable and second for creating List<string>这将导致多次迭代,首先是填充DataTable ,其次是创建List<string>

Please try this请试试这个

DataTable dt = new DataTable();
da.Fill(dt);
Users = dt.AsEnumerable().Select(n => n.Field<string>(0)).ToList();

If types in your database are different, you can use this, it will accept all types.如果您的数据库中的类型不同,您可以使用它,它将接受所有类型。

var dataTable= new DataTable();
dataTable.Fill(dataTable);
var users = dataTable.AsEnumerable().Select(n => n.ItemArray).ToList();

You will obtain result as a nice list of elements:您将获得作为一个很好的元素列表的结果:

[[3,"Adam","Smith","adamSmith@gmail.com","Kokos",1],
[5,"Dominika","Smith","dominikaSmith@gmail.com","Domis",2]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM