SQL query result to array/List

  • A+
Category:Languages

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 ?


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: