Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从SQL获取数据并放入列表_C#_.net_Sql - Fatal编程技术网

C# 从SQL获取数据并放入列表

C# 从SQL获取数据并放入列表,c#,.net,sql,C#,.net,Sql,我从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

我从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();
}
这张桌子看起来像这样

援助、出价、姓名

**

  • 问题
**

我被困在如何将项目添加到列表中,这也是最佳实践吗?

list fruits=new list();
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);
}
while(reader.Read()) { 水果f=新水果(); f、 aID=(字符串)读卡器[“aID”]; f、 bID=(字符串)读卡器[“bID”]; f、 名称=(字符串)读取器[“名称”]; 添加(f); }
你实际上需要从读者那里阅读,而这正是你没有做的。但是,请注意DBNulls

因此,假设您的自定义列表具有添加功能,您可以执行以下操作

while(reader.Read())
{
    Fruitee.add(reader["aID"], reader["bID"], reader["name"]);
}
var list=newlist();
while(reader.Read())
{
添加(new Fruit(){aID=reader[“aID”].ToString(),bID=reader[“bID”].ToString(),name=reader[“name”].ToString()});
}
var Fruitee=new List();
while(reader.Read())
{
添加(新的水果(){aID=reader[“aID”].ToString(),bID=reader[“bID”].ToString(),name=reader[“name”].ToString());
}

不能使用Fruitee.add,因为它不是一个列表。这就是为什么我在自定义列表有一个add函数的情况下声明。是的,但是Fruitee变量是一个存储这些参数的类。即使它有一个add函数,它将存储在哪里?它需要在该类中有一个列表来存储这些参数。
var list = new List<Fruit>();

  while (reader.Read())
  {
         list.Add(new Fruit() { aID = reader["aID"].ToString(), bID = reader["bID"].ToString(), name = reader["name"].ToString() });
  }
var Fruitee = new List<Fruit>();

while (reader.Read())
{
    Fruitee.Add(new Fruit() { aID = reader["aID"].ToString(), bID = reader["bID"].ToString(), name = reader["name"].ToString() });
}