【问题标题】:how do i convert IEnumerable<MyClass> to DataTable very fast?如何快速将 IEnumerable<MyClass> 转换为 DataTable?
【发布时间】:2011-09-23 00:01:37
【问题描述】:

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

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

非常感谢您。

【问题讨论】:

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


    【解决方案1】:

    详细解释见thisartice。

    核心代码示例

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

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

    【讨论】:

    • 这对我不起作用,因为我说过我收到 IEnumerable 作为匿名原因我必须过滤我的结果,这是我必须升级的旧代码。
    • 还有一件事,这个方法不支持Nullable,我得把它改成可以为空的。
    • 我不得不稍微修改代码以使用我的 WPF 应用程序,但是完美的答案
    猜你喜欢
    • 2018-03-04
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 2011-09-30
    相关资源
    最近更新 更多