2012-02-04 62 views
3
string str = "Select bd_id from [Active]"; 
ds = new DataSet(str); 
da = new SqlDataAdapter(str, con); 
da.Fill(ds); 

我想補充一點,我得到的ID'S的列表形式的數據集:如何將數據集中的值添加到列表中?

bd_id 
    1 
    2 
    3 

成通用列表,項目

我如何去這樣做的一樣嗎?

回答

9

Makue使用LINQ to DATATABLE將爲您輕鬆完成任務。

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

怎麼會,幫助我?將有助於如果你可以站點幾個步驟 – vini 2012-02-04 06:29:18

+1

@vini - 你現在可以看到示例代碼...你也可以谷歌LINQ到datable並獲得有關此信息的詳細信息..我希望你知道C#的LINQ# – 2012-02-04 06:32:32

+0

它完成謝謝: ) – vini 2012-02-04 06:36:31

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; 
    } 
相關問題