我如何非常快速地将IEnumerable <myclass>转换为DataTable?</myclass>

时间:2011-06-26 14:46:22

标签: asp.net c#-4.0 datatable anonymous-types

我熟悉将任何IEnumerable转换为DataTable的反射方法,但它非常慢! 当我得到的数据不是很大但是大块数据时,我的浏览器反应非常慢,因为它处理的数据非常复杂。

我需要提高我的表现,我该怎么做? PS:检查过LazyLoading DataTable没有成功,也许有人会告诉我该怎么做?

非常感谢你。

1 个答案:

答案 0 :(得分:2)

有关详细说明,请参阅this文章。

核心代码示例

 public static DataTable ToDataTable<T>(this IEnumerable<T> collection)
    {
        DataTable dt = new DataTable();
        Type t = typeof(T);
        PropertyInfo[] pia = t.GetProperties();
        //Create the columns in the DataTable
        foreach (PropertyInfo pi in pia)
        {
            if ((pi.PropertyType.IsGenericType) )
            {
                Type typeOfColumn = pi.PropertyType.GetGenericArguments()[0];
                dt.Columns.Add(pi.Name, typeOfColumn);
            }
            else
                dt.Columns.Add(pi.Name, pi.PropertyType);
        }
        //Populate the table
        foreach (T item in collection)
        {
            DataRow dr = dt.NewRow();
            dr.BeginEdit();
            foreach (PropertyInfo pi in pia)
            {
                dr[pi.Name] = pi.GetValue(item, null);
            }
            dr.EndEdit();
            dt.Rows.Add(dr);
        }
        return dt;
    }
}

为什么您认为数据转换会减慢您的应用?你的个人资料了吗?