【问题标题】:add non specific number of dataset rows into a list将非特定数量的数据集行添加到列表中
【发布时间】:2019-03-06 12:37:58
【问题描述】:

我正在尝试使用 foreach 将数据集中非特定数量的行插入到列表中。但我不确定如何将非特定数量的项目添加到数据集中的列表中。

public void DeviceReset(string r)
{
    conn.Open();
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = 
"SELECT installation_id FROM masterinstallationmaps WHERE masterinstallation_id = '" + r + "' ";
    cmd.ExecuteNonQuery();

    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);

我正在从我的 masterinstallationmap 表中挑选 installation_id,如果它包含超过 0 行,它应该运行 foreach 以将行放入列表中,否则它应该运行一个 foreach 只将 1 项输入到列表中。

List<int> instIdList = new List<int>();
if (ds.Tables[0].Rows.Count > 0)
{
    foreach (DataRow row in ds.Tables[0].Rows)
    {
        //How to insert all rows from the dataset?
    }
}
else
{
    instIdList.Add(1);
}

else 语句可以正常工作,但如果 Dataset 的行数超过 0,则不会发生任何事情。

我不确定要在 foreach 中添加什么:

foreach (DataRow row in ds.Tables[0].Rows)
{
    //How to insert all rows from the dataset?
}

【问题讨论】:

    标签: c# list foreach dataset


    【解决方案1】:

    你为什么不能像这样添加值

    foreach (DataRow row in ds.Tables[0].Rows)
    {
        instIdList.Add(Convert.ToInt32(row["installation_id"])); 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多