我从sql获取数据并将其放入列表中.这是我现在正在尝试的,
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 }
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(); }
表看起来像这样,
aID,bID,名称
**
>问题
**
我被困在如何将项目添加到列表中,这也是最佳做法?
解决方法
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); }