Amehiny Amehiny - 4 months ago 10
C# Question

How to load data into a List

I am loading data from the database to the c# console application but how should I put them on a list.

The part of my code

using (SqlConnection sourceConnection =
new SqlConnection(connectionString))
{
sourceConnection.Open();

SqlDataReader myReader = null;

SqlCommand myCommand = new SqlCommand(
"SELECT * FROM " +
"dbo.Users;",
sourceConnection);

myReader = myCommand.ExecuteReader();

//long countStart = System.Convert.ToInt32(myCommand.ExecuteScalar());
while (myReader.Read())
{
Console.WriteLine(myReader["Id"].ToString());
Console.WriteLine(myReader["Name"].ToString());
}


I get them printed in the console but how should I put them on a list .

var listOfUsers = new List<User>();

Answer

Lets assume that you have a Users Class that represents the type of elements in the list.

public class Users
{
    public string Id { get; set; }

    public string Name { get; set; }
}

Then you can in your method add them to a List, which will be represented by two columns:

public void addUsersToList()
{

    using (SqlConnection sourceConnection =
                   new SqlConnection(connectionString))
        {
            sourceConnection.Open();

            SqlDataReader myReader = null;

            SqlCommand myCommand = new SqlCommand(
                "SELECT * FROM " +
                "dbo.Users;",
                sourceConnection);

            myReader = myCommand.ExecuteReader();

            //long countStart = System.Convert.ToInt32(myCommand.ExecuteScalar());
            List<Users> myList = new List<Users>();
            while (myReader.Read())
            {
                myList.Add(new Users { Id = myReader["Id"].ToString(), 
                            Name = myReader["Name"].ToString() });
            } 

        }
}