Amehiny
Amehiny

Reputation: 135

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

Upvotes: 0

Views: 5928

Answers (2)

Osman Esen
Osman Esen

Reputation: 1696

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

        }
}

Upvotes: 3

John
John

Reputation: 3702

There's not much else you can do but create a user, fill its properties and add it to a list...

            while (myReader.Read())
            {
                User user = new User();
                user.Id = myReader["Id"].ToString();
                user.Name = myReader["Name"].ToString();
                listOfUsers.Add(user);
            } 

Upvotes: 2

Related Questions