我从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
}
这就是我从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();
}
表格如下所示,
aID,bID,名称
**
**
我遇到了如何将项目添加到列表中而也是最佳做法?
答案 0 :(得分:18)
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);
}
答案 1 :(得分:3)
var list = new List<Fruit>();
while (reader.Read())
{
list.Add(new Fruit() { aID = reader["aID"].ToString(), bID = reader["bID"].ToString(), name = reader["name"].ToString() });
}
答案 2 :(得分:1)
var Fruitee = new List<Fruit>();
while (reader.Read())
{
Fruitee.Add(new Fruit() { aID = reader["aID"].ToString(), bID = reader["bID"].ToString(), name = reader["name"].ToString() });
}
答案 3 :(得分:-1)
您需要从读者那里读取,这就是您没有做的事情。但是,请注意DBNulls。
因此,假设您的自定义列表具有添加功能,您可以执行以下操作。
while(reader.Read())
{
Fruitee.add(reader["aID"], reader["bID"], reader["name"]);
}