1

I can convert SqlDataReader to a list using a loop While(dr.Read()).

But, I need to convert SqlDataReader to a list.

Pseudo code:

con.Open();

string sqlBU = "select top 10 fname, iduser from users";

SqlCommand cmd = new SqlCommand(sqlBU, con);

using (SqlDataReader dr2 = cmd.ExecuteReader())
{
    List<ListOfClass> customers = dr2.ToList();
}

dataGridView1.DataSource = lOfClass;

con.Close();

Class:

 public class ListOfClass
 {
    public string fname { get; set; }
    public string iduser { get; set; }
 }
1

1 Answer 1

1
var timeSeries = new List<ListOfClass>();  
using (var reader = cmd.ExecuteReader())
{
   if (reader.HasRows)
  {
      timeSeries = reader.Cast<IDataRecord>()
           .Select(r => new ListOfClass
             {
                 fname = (string)r["fname"],
                            iduser = (string)r["iduser"]
             }).ToList();
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

a while loop here would look more elegant.
@AmitKumarGhosh but the question was to do it without the loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.