没有办法do it directly in one step,因此您必须使用数据表的Rows 集合和DataRow 的indexer property 在循环中手动更改值:
DataTable dt = ...
String[] destinationFiles = ...
Int32 destinationFileColumnIndex = 2;
if (dt.Rows.Count != destinationFiles.Length)
throw new Exception("Lengthes are inconsistent");
for (int i = 0; i < destinationFiles.Length; i++)
{
dt.Rows[i][destinationFileColumnIndex] = destinationFiles[i];
}
如果destinationFiles 的类型与String 不同,则DataTable 列应为changed to have appropriate type,或者您必须将该类型的值转换为字符串。
要实现它,您应该调用.ToString() 方法,如果它是correctly implemented:
SomeType[] destinationFiles = ...
// ...
dt.Rows[i][destinationFileColumnIndex] = destinationFiles[i].ToString();
或手动form the string设置:
SomeType cur = destinationFiles[i];
dt.Rows[i][destinationFileColumnIndex] = String.Format("{0} and {1}",
cur.Prop1,
cur.Prop2);
编辑:
不幸的是没有直接方法,但是有Extension Methods这样的东西:
public static class DataColumnExtensions
{
// Will work with both the arrays and lists
public static void SetValues<T>(this DataColumn column, IList<T> values)
{
if (column == null)
throw new ArgumentNullException("column");
if (values== null)
throw new ArgumentNullException("values");
DataTable dt = column.Table;
if (dt.Rows.Count != values.Count)
throw new Exception("Lengths are inconsistent");
for (int i = 0; i < values.Count; i++)
{
dt.Rows[i][column] = values[i];
}
}
}
并像这样使用它:
dt.Columns[2].SetValues(new String[] {....});
只需将其放入与您的代码相同的命名空间中,或者作为一种更好的做法,将其放入一些适当命名的命名空间中,并仅在您需要时使用 using AppropriatelyNamedNamespace;。