我需要使用单列查询的结果集填充一个通用的字符串List。我有这个代码:
private List<String> _mammalsList;
. . .
private void LoadMammalStringList()
{
_mammalsList = new List<string>();
using (SqlConnection con = new SqlConnection(PlatypusUtils.DuckbillConnStr))
{
using (SqlCommand cmd = new SqlCommand(PlatypusUtils.SelectMammalIdQuery, con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
// Now that the data is in dt, how can I pull it out of there and put it into the List<String>?
}
}
}
}
...但不知道如何访问返回的数据集。我怎么能这样做?
答案 0 :(得分:0)
取代“现在怎样?”评论此代码:
foreach (DataRow row in dt.Rows)
{
_mammalsList.Add(row.ItemArray[0].ToString());
}
在上下文中:
private void LoadMammalsStringList()
{
_mammalsList = new List<string>();
using (SqlConnection con = new SqlConnection(PlatypusUtils.DuckbillConnStr))
{
using (SqlCommand cmd = new SqlCommand(PlatypusUtils.SelectMammalIdQuery, con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
_mammalsList.Add(row.ItemArray[0].ToString());
}
}
}
}
}
正如Momar所暗示,这也有效:
//foreach (DataRow row in dt.Rows)
//{
// _membersList.Add(row.ItemArray[0].ToString());
//}
_mammalsList = dt.AsEnumerable()
.Select(r => r.Field<string>("mammalId"))
.ToList();
我不知道哪种方法更可取。