Jeya Suriya Muthumari
Jeya Suriya Muthumari

Reputation: 2021

SQL query result to array/List

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 ?

Upvotes: 2

Views: 7021

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460028

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

Upvotes: 4

Oilid
Oilid

Reputation: 151

Try this :

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

Upvotes: 4

Marc Gravell
Marc Gravell

Reputation: 1062510

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

Upvotes: 8

apomene
apomene

Reputation: 14389

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

Upvotes: 5

Related Questions