2011-12-26 11 views
2

私はこのpostを見つけましたが、ユーザーとほとんど同じシナリオがありますが、.NET 2.0フレームワークのみを使用しています。以下のコードは、datatableをlistに変換します。.NET 2.0を使用してDataTableをリストに変換する最速の方法

ありがとうございます。

namespace DataTableToListTest 
{ 
    public partial class MainForm : Form 
    { 
       // Just a sample class 
     class MyType 
     { 
      private int _foo; 
      private string _bar; 

      public MyType(int foo, string bar) 
      { 
       _foo = foo; 
       _bar = bar; 
      } 

      public int Foo 
      { 
       get { return _foo; } 
       set { _foo = value; } 
      } 

      public string Bar 
      { 
       get { return _bar; } 
       set { _bar = value; } 
      } 
     } 

     public MainForm() 
     { 
      InitializeComponent(); 
      dataGridView1.DataSource = GetDataSource();   
     } 

     List<MyType> GetDataSource() 
     { 
      DataTable table = GetTable(); 

      for (int i = 0; i < 5000; i++)   
       table.Rows.Add(i, "Row " + i);  

      List<MyType> data = new List<MyType>(table.Rows.Count); 

      foreach (DataRow row in table.Rows)  
       data.Add(new MyType((int)row[0], (string)row[1])); 
      return data; 
     } 


       // Suppose this method queries the database 
     DataTable GetTable() 
     {   
      DataTable table = new DataTable(); 
      table.Columns.Add("Foo", typeof(int)); 
      table.Columns.Add("Bar", typeof(string)); 

      return table; 
     } 
    } 
} 
+1

を考えることはできませんあなたの現在のコードは、実際にここでパフォーマンスのボトルネックを持っていますか? –

+0

正直言って、私は私のアプリケーションでこれを試していません。このアプローチを使用してデータベースで照会されるサンプル・オブジェクトは、従業員データです。私はちょうどデモのためにこのMyTypeクラスを使用しました... – yonan2236

+0

@ yonan2236:あなたはいつもより速く何かを見つける前にいくつかのコードを試して測定する必要があります。 –

答えて

2

私は、他の最適化の

int count = table.Rows.Count; 
List<MyType> data = new List<MyType>(count); 

for(int i = 0 ; i <count; i ++) 
{ 
    DataRow row = tables.Rows[i]; 
    data.Add(new MyType((int)row[0], (string)row[1])); 
} 

return data; 
関連する問題