将动态列表转换为数据表c#

时间:2014-02-10 09:04:32

标签: c#

正在搜索并破解我的大脑如何将动态列表转换为数据库, c#,请指教,谢谢

List<dynamic>dlist=new List<dynamic>

DataTable 

8 个答案:

答案 0 :(得分:5)

以下是将任何列表对象转换为数据表的方法。

 public DataTable ConvertToDataTable<T>(IList<T> data)
    {
        PropertyDescriptorCollection properties =
           TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;

    }

http://social.msdn.microsoft.com/Forums/vstudio/en-US/6ffcb247-77fb-40b4-bcba-08ba377ab9db/converting-a-list-to-datatable?forum=csharpgeneral

答案 1 :(得分:3)

 public DataTable ToDataTable<T>(dynamic items)
    {

        DataTable dtDataTable = new DataTable();
        if (items.Count == 0) return dtDataTable;

        ((IEnumerable)items[0]).Cast<dynamic>().Select(p => p.Name).ToList().ForEach(col => { dtDataTable.Columns.Add(col); });

        ((IEnumerable)items).Cast<dynamic>().ToList().
            ForEach(data =>
            {
                DataRow dr = dtDataTable.NewRow();
                ((IEnumerable)data).Cast<dynamic>().ToList().ForEach(Col => { dr[Col.Name] = Col.Value; });
                dtDataTable.Rows.Add(dr);
            });
        return dtDataTable;
    }

答案 2 :(得分:2)

我不知道为什么你需要这个,但是,你可以使用这个ObjectShredder使用反射,它可以将任何东西转换为DataTable,所以即使是动态或匿名类型:

Implement CopyToDataTable<T> Where the generic Type T Is Not a DataRow

但是,我的建议是为扩展方法CopyToDataTable命名,但例如CopyAnyToDataTable,以避免与现有扩展方法CopyToDataTable发生冲突。

答案 3 :(得分:0)

使用此功能,

public static DataTable ConvertToDatatable<T>(this IList<T> data)
{
    PropertyDescriptorCollection props =
        TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for(int i = 0 ; i < props.Count ; i++)
    {
        PropertyDescriptor prop = props[i];
        table.Columns.Add(prop.Name, prop.PropertyType);
    }
    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;        
    }

答案 4 :(得分:0)

如果基础类型为ExpandoObject,则需要检查IDictionary,而不是通过反射进行检查。希望这对以后的人有所帮助:

    public static DataTable ConvertToDataTable<T>(IEnumerable<T> data)
    {
        DataTable table = new DataTable();
        foreach (T item in data)
        {
            if (item is IDictionary<string, object> dict)
            {
                foreach (var key in dict)
                {
                    table.Columns.Add(key.Key, key.Value?.GetType() ?? typeof(object));
                }
                break;
            }
            foreach (var prop in typeof(T).GetProperties())
            {
                table.Columns.Add(prop.Name, prop.PropertyType);
            }
            break;
        }

        DataRow row = null;
        foreach (T item in data)
        {
            if (item is IDictionary<string, object> dict)
            {
                row = table.NewRow();
                foreach (var key in dict)
                {
                    row[key.Key] = key.Value;
                }
                table.Rows.Add(row);
                continue;
            }

            row = table.NewRow();
            foreach (var prop in typeof(T).GetProperties())
            {
                row[prop.Name] = prop.GetValue(item);
            }
            table.Rows.Add(row);
        }
        return table;
    }

答案 5 :(得分:0)

我认为您看起来像这样。希望它为您工作。

   List<dynamic> dlist=new List<dynamic> 
    var json = JsonConvert.SerializeObject(dlist);
                DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));

答案 6 :(得分:0)

使用C#将动态列表对象转换为DataTable

 public DataTable DynamicToDT(List<object> objects)
        {
            DataTable dt = new DataTable("StudyRecords"); // Runtime Datatable          
            string[] arr = { "Name", "Department", "CollegeName", "Address" };// Column Name for DataTable
            if (objects != null && objects.Count > 0)
            {
                for (int i = 0; i < objects.Count; i++)
                {
                    dt.Columns.Add(arr[i]);
                    if (i == 0)
                    {
                        var items = objects[0] as IEnumerable<string>;
                        foreach (var itm in items)
                        {
                            DataRow dr1 = dt.NewRow(); // Adding values to Datatable  
                            dr1[arr[i]] = itm;
                            dt.Rows.Add(dr1);
                        }
                    }
                    else
                    {
                        var items = objects[i] as IEnumerable<string>;
                        int count = 0;
                        foreach (var itm in items)
                        {
                            dt.Rows[count][arr[i]] = itm;
                            count++;
                        }
                    }
                }

                return dt; // Converted Dynamic list to Datatable  
            }
            return null;
        }

答案 7 :(得分:0)

public static DataTable DynamicToDT(List objects)

bool isVisible(String educationLevelName, int examinationNameID) =>
    (educationLevelName == "H.S.C or Equivalent" &&
        (examinationNameID != 8 && examinationNameID != 11)) ||
    (educationLevelName == "S.S.C or Equivalent" && examinationNameID != 3);