2010-10-12 77 views
1

下面的代碼發送到列表框:從數據表數組,沒有循環

  DataTable dt = new DataTable(); 

     DataColumn dc = new DataColumn("BestSite", typeof(string)); 

     dt.Columns.Add(dc); 

     for (int i = 1; i <= 10; i++) 
     { 
      DataRow dr = dt.NewRow(); 
      dr[0] = i.ToString() + " = stackoverflow"; 
      dt.Rows.Add(dr); 
     }//EndFor 

     var Query = from mycolumn in dt.AsEnumerable() 
        where mycolumn.Field<string>("BestSite") != string.Empty 
        select mycolumn; 


     listBox1.DataSource = Query.AsDataView(); 

     listBox1.DisplayMember = "BestSite"; 

轉移到陣列應該是什麼? 沒有循環

string[] myvalue = new string[Query.AsDataView().Count]; 

回答

1

如果我理解正確你的問題......

string[] myvalue = Query.Select(i => i.Field<string>("BestSite")).ToArray(); 
+0

你仍然可以使用LINQ做到這一點,再次檢查答案。 – 2010-10-12 03:08:56

1

終於實現

正確答案:

 private string ConvertToString(DataRow dr) 
    { 
     return Convert.ToString(dr[0]); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 

     DataTable dt = new DataTable(); 

     DataColumn dc = new DataColumn("BestSite", typeof(string)); 

     dt.Columns.Add(dc); 

     for (int i = 1; i <= 10; i++) 
     { 
      DataRow dr = dt.NewRow(); 
      dr[0] = i.ToString() + " = stackoverflow"; 
      dt.Rows.Add(dr); 
     }//EndFor 

     //var Query = from mycolumn in dt.AsEnumerable() 
     //   where mycolumn.Field<string>("BestSite") != string.Empty 
     //   select mycolumn; 

     DataRow[] myrow = new DataRow[dt.Rows.Count]; 
     dt.Rows.CopyTo(myrow, 0); 

     string[] myString = Array.ConvertAll(myrow, new Converter<DataRow, string>(ConvertToString)); 


     foreach (string a in myString) 
     { 
      listBox1.Items.Add(a); 
     } 

    }