【问题标题】:How do I Convert List<T> or IEnumerable<T> to DataTable [duplicate]如何将 List<T> 或 IEnumerable<T> 转换为 DataTable [重复]
【发布时间】:2011-09-30 21:50:36
【问题描述】:

可能重复:
Convert IEnumerable to DataTable

我只想通过扩展方法或 Util 类将 List 或 IEnumerable 转换为 DataTable。

【问题讨论】:

  • 你能更精确一点吗?您想创建一个新的数据表,其中包含 T 实例的属性/字段的快照,还是想要某种代理对象通过类似数据表的形状来表示您的 T 实例?
  • 你为什么要这样做呢?可能有更好的方法。

标签: .net


【解决方案1】:

我使用以下扩展方法从 IEnumerable 生成数据库。 希望这会有所帮助。

        public static DataTable ToDataTable<TSource>(this IEnumerable<TSource> source)
        {
            var tb = new DataTable(typeof (TSource).Name);
            var props = typeof (TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (var prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }

            foreach (var item in source)
            {
                var values = new object[props.Length];

                for (var i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }
                tb.Rows.Add(values);
            }
            return tb;
        }

    public static Type GetCoreType(Type t)
    {
        return t != null && IsNullable(t) 
               ? (!t.IsValueType ? t : Nullable.GetUnderlyingType(t)) : t;
    }


    public static bool IsNullable(Type t)
    {
        return !t.IsValueType || (t.IsGenericType 
               && t.GetGenericTypeDefinition() == typeof(Nullable<>));
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-24
    • 2021-12-02
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 2018-08-04
    • 2011-01-17
    相关资源
    最近更新 更多