开发者

DataTable that has List<string> in it

开发者 https://www.devze.com 2023-03-07 17:27 出处:网络
I\'m using Linq to return data from an XML file to a DataTable and that works. But now I\'m trying to modify the code to loop through the DataTable. I created a custom class to model the data and have

I'm using Linq to return data from an XML file to a DataTable and that works. But now I'm trying to modify the code to loop through the DataTable. I created a custom class to model the data and have a List in my model. When I loop through the DataTable to display records it displays System.Collections.Generic.List`1[System.String] instead of the actual data. I'm not sure what to search to find the answer.

Snippet:

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

The myList column is the List. I hope this makes sense.

Edited:

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;
    }


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

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

I had to do the above to get it to work. I then add hobby to my output array.

0

精彩评论

暂无评论...
验证码 换一张
取 消