[英]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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.