2011-05-23 57 views
0

我正在使用Linq將XML文件中的數據返回到DataTable並且工作正常。但是現在我試圖修改代碼來循環訪問DataTable。我創建了一個自定義類來建模數據,並在我的模型中有一個List。當我通過DataTable循環顯示記錄時,它顯示System.Collections.Generic.List`1 [System.String]而不是實際的數據。我不知道要搜索什麼才能找到答案。其中有列表<string>的DataTable

段:

foreach (DataRow row in tbl.Rows) 
{ 
    myList = row["myList"] + ", " + myList; 
} 

的myList中列列表。我希望這是有道理的。

編輯:

public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist) 
    { 
     DataTable dtReturn = new DataTable(); 

     // column names 
     PropertyInfo[] oProps = null; 

     if (varlist == null) return dtReturn; 

     foreach (T rec in varlist) 
     { 
       // Use reflection to get property names, to create table, Only first time, others will follow 
       if (oProps == null) 
       { 
        oProps = ((Type)rec.GetType()).GetProperties(); 
        foreach (PropertyInfo pi in oProps) 
        { 
         Type colType = pi.PropertyType; 

         if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) 
         { 
          colType = colType.GetGenericArguments()[0]; 
         } 

         dtReturn.Columns.Add(new DataColumn(pi.Name, colType)); 
        } 
       } 

       DataRow dr = dtReturn.NewRow(); 

       foreach (PropertyInfo pi in oProps) 
       { 
        dr[pi.Name] = pi.GetValue(rec, null) == null ?DBNull.Value :pi.GetValue 
        (rec,null); 
       } 

       dtReturn.Rows.Add(dr); 
     } 
     return dtReturn; 
    } 

回答

0
hobbiesList = (List<string>)row["hobbies"]; 

foreach (var item in hobbiesList) 
{ 
    hobbies.Add(item.ToString()); 
} 
hobby = string.Join(", ", hobbies.ToArray()); 
hobbies.Clear(); 

我不得不做以上才能正常工作。然後我將愛好添加到我的輸出數組中。

相關問題