-1

我需要List<string>[]在 C# 中将类型的列表数组转换为 Datatable。

我发现了许多与List<string[]>Datatable 转换相关的主题,但没有关于我需要的转换。

伪代码:

//Retrieve data from MySQL server 
db.Select(category, productID);
//populate List<string>[] array 
list[0] = db.ListQuery[0];
list[1] = db.ListQuery[1];

//convert list[] to Datatable
.....

任何帮助深表感谢。

4

2 回答 2

1

如果我理解你的问题是正确的,你的意思是这样的吗?

string category = "Category";
string productId = "ProductId";
List<string[]> tempList = db.Select(category, productID); //Not necessarily correct (I'm not familiar with MySQL). Do what you need to do to create the List<string[]>
DataTable table = new DataTable();
DataRow row;
table.Columns.Add(category);
table.Columns.Add(productId);
foreach (string[] s in tempList)
{
   row = table.NewRow();
   row[category] = s[0];
   row[productId] = s[1];
   table.Rows.Add(row);
}
于 2013-04-14T05:43:20.077 回答
-1
DataTable dataTable = new DataTable();
            List<MemberInfo> props = typeof(T).GetFields().Select(objField => (MemberInfo)objField).ToList();
            props.AddRange(typeof(T).GetProperties().Select(objField => (MemberInfo)objField));

            if (props.Count > 0)
            {
                Type t;
                bool tIsField = false;
                for (int iCnt = 0; iCnt < props.Count; iCnt++)
                {
                    var prop = props[iCnt];
                    tIsField = prop.MemberType == MemberTypes.Field;
                    dataTable.Columns.Add(prop.Name, tIsField ? ((FieldInfo)prop).FieldType : ((PropertyInfo)prop).PropertyType);
                }
                foreach (T item in data)
                {
                    DataRow dr = dataTable.NewRow();

                    foreach (var field in props)
                    {
                        tIsField = field.MemberType == MemberTypes.Field;
                        object value = tIsField ? ((FieldInfo)field).GetValue(item) : ((PropertyInfo)field).GetValue(item, null);
                        dr[field.Name] = value;
                    }
                    dataTable.Rows.Add(dr);
                }
            }
            return dataTable;
于 2014-04-03T07:13:59.330 回答