如何将数据集中的值添加到列表中?

时间:2012-02-04 06:19:07

标签: c# asp.net linq ado.net

string str = "Select bd_id from [Active]";
ds = new DataSet(str);
da = new SqlDataAdapter(str, con);
da.Fill(ds);

我想在表单中添加我得到的数据集,其中包含ID列表:

bd_id
   1
   2
   3

作为项目进入通用LIST

我如何做同样的事情?

2 个答案:

答案 0 :(得分:9)

使用 LINQ to DATATABLE 可以轻松完成任务。

DataTable dtDetails = ds.Table[0];
List<int> lstExcelCurrencyCode =
                    (from dr in dtDetails.AsEnumerable()
                      select  dr.Field<int>("bd_id")).ToList<int>();

答案 1 :(得分:3)

    SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
    DataSet ds = new DataSet();
    sda.Fill(ds, "table");
    IList<T> lists = GetList<T>(ds.Tables["table"]);

    //DataTable Convert To List Method
    public List<T> GetList<T>(DataTable table)
    {
        List<T> list = new List<T>();
        T t = default(T);
        PropertyInfo[] propertypes = null;
        string tempName = string.Empty;
        foreach (DataRow row in table.Rows)
        {
            t = Activator.CreateInstance<T>();
            propertypes = t.GetType().GetProperties();
            foreach (PropertyInfo pro in propertypes)
            {
                tempName = pro.Name;
                if (table.Columns.Contains(tempName))
                {
                    object value = row[tempName];
                    if (value.GetType() == typeof(System.DBNull))
                    {
                        value = null;
                    }
                    pro.SetValue(t, value, null);
                }
            }
            list.Add(t);
        }
        return list;
    }