开发者

C# Convert string array to dataset

I have an array of strings and need to convert them to a dataset. Is there some shortcut way to do this? For example:

string[] results = GetResults();    
DataSet myDataSet = new DataSet();

results = myDataSet.ToDataSet();  // Convert array to data set

I’m not too bothered about formatting 开发者_开发技巧or structure.


I can't see any value in this but if you really must do as you request, the following code will create a dataset with a single table that has a single column and a row per item in the array.

internal static class Program
{
    private static void Main(string[] args)
    {
        string[] array = new [] { "aaa", "bbb", "ccc" };
        DataSet dataSet = array.ToDataSet();
    }

    private static DataSet ToDataSet(this string[] input)
    {
        DataSet dataSet = new DataSet();
        DataTable dataTable = dataSet.Tables.Add();
        dataTable.Columns.Add();
        Array.ForEach(input, c => dataTable.Rows.Add()[0] = c);
        return dataSet;
    }
}


dataTable.LoadDataRow(array, true);


Other examples didn't work for me. Found this:

  public DataTable ConvertArrayToDatatable(MarketUnit[] arrList)
    {
        DataTable dt = new DataTable();
        try
        {
            if (arrList.Count() > 0)
            {
                Type arrype = arrList[0].GetType();
                dt = new DataTable(arrype.Name);

                foreach (PropertyInfo propInfo in arrype.GetProperties())
                {
                    dt.Columns.Add(new DataColumn(propInfo.Name));
                }

                foreach (object obj in arrList)
                {
                    DataRow dr = dt.NewRow();

                    foreach (DataColumn dc in dt.Columns)
                    {
                        dr[dc.ColumnName] = obj.GetType().GetProperty(dc.ColumnName).GetValue(obj, null);
                    }
                    dt.Rows.Add(dr);

                }
            }


            return dt;
        }
        catch (Exception ex)
        {
            return dt;
        }

    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜