2

Following is the C# code for querying the DB to get the list of users id:

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();

Output: 5629

Actually, the list of Users having grpid = 180 are 5629, 5684, 5694.

How can I read the results in a list or an array ?

CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
Jeya Suriya Muthumari
  • 1,947
  • 3
  • 25
  • 47

4 Answers4

8

simply:

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

However, you might find a tool like "Dapper" a useful time saver here

var results = con.Query<int>("Select userid from UserProfile where grpid=@id",
    new { id }).AsList();
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
5

Simply define a List, and use like:

List<string> Users = new List<string>();
using (SqlDataReader reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        Users.Add(reader[0].ToString());
    }
}
apomene
  • 14,282
  • 9
  • 46
  • 72
4

Try this :

var userIds = new List<int>();
using (var reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        userIds.Add(reader.GetInt32(0));
    }
}
Oilid
  • 141
  • 1
  • 8
4

You could use this extension method:

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;
    }
}

Now you can use it in this way:

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>();
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939