1. 程式人生 > >c# 從DataTable中取得指定資料

c# 從DataTable中取得指定資料

從DataTable中取得指定資料

		private int idx = 1000000;
		private int fndIdx = 0;
		private DataTable GetData( )
		{
			fndIdx = int.Parse( textBox1.Text );

			DataTable dt = new DataTable( );
			dt.Columns.Add( "id", typeof( int ) );
			dt.Columns.Add( "name", typeof( string ) );
			dt.Columns.Add( "type", typeof( string ) );
			dt.PrimaryKey = new DataColumn[ ] { dt.Columns["id"], dt.Columns["name"] };
			for ( int i = 0; i < idx; i++ )
			{
				dt.Rows.Add( i, i.ToString( ), i % 3 );
				dt.Rows.Add( i, i.ToString( ) + "A", i % 3 );
			}
			return dt;
		}

		private void button1_Click( object sender, EventArgs e )
		{
			DataTable dt = GetData( );
			DateTime tStart = DateTime.Now;
			string type = dt.Select( "id = " + fndIdx + " and  name = '" + fndIdx + "'" )[0]["type"].ToString( );
			label1.Text = String.Format( "{0}毫秒,type:{1}", ( DateTime.Now - tStart ).Milliseconds, type );

		}

		private void button2_Click( object sender, EventArgs e )
		{
			DataTable dt = GetData( );
			string type = "";
			DateTime tStart = DateTime.Now;
			foreach ( DataRow dr in dt.Rows )
			{
				if ( Convert.ToInt32( dr["id"] ) == fndIdx && Convert.ToInt32( dr["name"] ) == fndIdx )
				{
					type = dr["type"].ToString( );
					break;
				}
			}
			label2.Text = String.Format( "{0}毫秒,type:{1}", ( DateTime.Now - tStart ).Milliseconds, type );
		}

		private void button3_Click( object sender, EventArgs e )
		{
			DataTable dt = GetData( );
			DateTime tStart = DateTime.Now;
			DataRow dr = dt.Rows.Find( new object[ ] { fndIdx, fndIdx } );
			string type = dr["type"].ToString( );
			label4.Text = String.Format( "{0}毫秒,type:{1}", ( DateTime.Now - tStart ).Milliseconds, type );
		}

button1是用DataTable.Select 檢索出指定的資料。此方法不加主鍵索引會非常慢,比下面兩個方法都慢。

button2是簡單的遍歷方法,效率低。

button3是用Rows.Find指定主鍵索引條件檢索資料,此方法必須有PrimaryKey主鍵索引,否則會報錯誤。