2011-06-26 62 views
0

我熟悉將任何IEnumerable轉換爲DataTable的反射方法,但它非常慢! 當我得到的數據量不是很大但數據量很大時,瀏覽器響應速度非常慢,因爲它處理的數據非常複雜。如何將IEnumerable <MyClass>轉換爲DataTable非常快?

我需要提高我的性能,我該怎麼做? PS:檢查LazyLoading DataTable在那裏沒有成功ether,也許有人會告訴我如何做到這一點?

非常感謝你提前。

回答

2

請參閱this artice的詳細說明。

核心代碼示例

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

爲什麼你認爲數據轉換減慢你的應用程序?你的個人資料呢?

+0

這對我來說不起作用因爲我說過我收到IEnumerable作爲匿名原因,我必須過濾我的結果,這是我必須升級的舊代碼。 – IamStalker

+0

還有一件事,這種方法不支持Nullable <>,我不得不改變它爲空。 – IamStalker

+0

我不得不稍微修改代碼以使用我的WPF應用程序,但是完美的答案 –

相關問題