Retrieving data from SQL and listing

I get data from SQL and put it in a list. that's what I'm trying now

public class Fruit //custom list { public string aID { get;set; } // can be more then 1 public string bID { get;set; } // only 2 but different aID public string name { get;set; } // only 1 for selection of aID and bID } 

and this is how I get data from sql,

 var Fruitee = new Fruit(); using (SqlConnection cn = new SqlConnection(CS())) { cn.Open(); SqlCommand sqlCommand= new SqlCommand("SELECT * FROM myTable", cn); SqlDataReader reader = sqlCommand.ExecuteReader(); while (reader.Read()) { Fruitee.add(reader["aID"], reader["bID"],reader["name"]) // ??? not sure what to put here as add is not available } cn.Close(); } 

The table looks like this:

aID, bID, name

**

  • Problem

**

I'm stuck, how to add items to the list, but is this the best practice?

+8
c # sql
source share
4 answers
 List<Fruit> fruits = new List<Fruit>(); while (reader.Read()) { Fruit f = new Fruit(); f.aID = (string) reader["aID"]; f.bID = (string) reader["bID"]; f.name = (string) reader["name"]; fruits.Add(f); } 
+15
source share
 var list = new List<Fruit>(); while (reader.Read()) { list.Add(new Fruit() { aID = reader["aID"].ToString(), bID = reader["bID"].ToString(), name = reader["name"].ToString() }); } 
+3
source share
 var Fruitee = new List<Fruit>(); while (reader.Read()) { Fruitee.Add(new Fruit() { aID = reader["aID"].ToString(), bID = reader["bID"].ToString(), name = reader["name"].ToString() }); } 
+1
source share

In fact, you need to read the reader and what you are not doing. However, keep in mind DBNulls.

So, if your custom list has an add function, you can do something like the following.

 while(reader.Read()) { Fruitee.add(reader["aID"], reader["bID"], reader["name"]); } 
-one
source share

All Articles