开发者

from datatable to array، no loop

开发者 https://www.devze.com 2023-01-19 09:27 出处:网络
Following Code for transmission to the list box is : DataTable dt = new DataTable(); DataColumn dc = new DataColumn(\"BestSite\", typeof(string));

Following Code for transmission to the list box is :

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

Transfer to array what should be? no loop

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


Finally realized

Correct answer :

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

    }


If I understood your question correctly...

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


This example assumes:
=> datatable is non zero length
=> values are "parsable" to double.

    coln = "PurchasePrice";

    double[] arr_val = Array.ConvertAll<DataRow, double>
        ( 
        dattbl.Select(),
        delegate (DataRow rw) { return 
        double.Parse(rw[coln].ToString()); }
        );
    
    // ... and for example 
    double total = arr_val.Sum();
0

精彩评论

暂无评论...
验证码 换一张
取 消