从数据表到数组,没有循环

时间:2010-10-12 00:03:39

标签: c# winforms linq arrays datatable

以下代码传输到列表框是:

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

2 个答案:

答案 0 :(得分:1)

如果我理解你的问题......

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

答案 1 :(得分: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);
        }

    }