SQL查询结果到数组/列表

时间:2018-05-07 09:55:54

标签: c# sql sqlcommand

以下是用于查询数据库以获取用户ID列表的C#代码:

int id;
con = new SqlConnection(Properties.Settings.Default.ConnectionStr);
con.Open();
id = 180;
SqlCommand command = new SqlCommand("Select userid from UserProfile where grpid=@id", con);
command.Parameters.AddWithValue("@id", id);

using (SqlDataReader reader = command.ExecuteReader())
{
    if (reader.Read())
    {
        Console.WriteLine(String.Format("{0}", reader["userid"]));
    }
}

con.Close();
  

输出:5629

实际上,Users grpid = 180的列表 5629,5684,5694

如何在列表或数组中读取结果?

4 个答案:

答案 0 :(得分:8)

简单地:

List<int> results = new List<int>();
using (SqlDataReader reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        results.Add((int)reader["userid"]));
    }
}
// use results

但是,您可能会发现像“Dapper”这样的工具可以节省时间

var results = con.Query<int>("Select userid from UserProfile where grpid=@id",
    new { id }).AsList();

答案 1 :(得分:5)

只需定义一个List,然后使用:

List<string> Users = new List<string>();
using (SqlDataReader reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        Users.Add(reader[0].ToString());
    }
}

答案 2 :(得分:4)

试试这个:

var userIds = new List<int>();
using (var reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        userIds.Add(reader.GetInt32(0));
    }
}

答案 3 :(得分:4)

您可以使用此扩展方法:

public static class DbExtensions
{
    public static List<T> ToList<T>(this IDataReader reader, int columnOrdinal = 0)
    {
        var list = new List<T>();
        while(reader.Read())
            list.Add((T)reader[columnOrdinal]);
        return list;
    }
}

现在您可以这样使用它:

List<int> userIdList;
using (var con = new SqlConnection(Properties.Settings.Default.ConnectionStr))
{
    using(var command = new SqlCommand("Select userid from UserProfile where grpid=@id", con))
    {
       command.Parameters.AddWithValue("@id", id);
       con.Open();
       using (SqlDataReader rd = command.ExecuteReader())
          userIdList = rd.ToList<int>();
    }
}