开发者

how do i convert IEnumerable<MyClass> to DataTable very fast?

开发者 https://www.devze.com 2023-03-15 06:53 出处:网络
I\'m familiar with the reflection method that converts any IEnumerable to DataTable, but it\'s very very slow!

I'm familiar with the reflection method that converts any IEnumerable to DataTable, but it's very very slow! When i get not huge but big chunk of data i get very slow browser reaction, because 开发者_如何转开发it's very complicated data to handle.

I need to boost my prefformance, how do i do it? PS: Checked LazyLoading DataTable no success there ether, maybe someone will show me how to do it?

Thank you very very much in advance.


See this artice for detailed explanation.

Core code sample

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

Why do you think that data converting slows your app? Did your profile it?

0

精彩评论

暂无评论...
验证码 换一张
取 消