【问题标题】:Set values of entire column of datatable from Array or List从数组或列表中设置数据表整列的值
【发布时间】:2014-10-25 22:37:22
【问题描述】:

我有一个包含 3 列的 DataTable:URL [string]、Date [DateTime]、DestinationFile [string]

我使用一种方法连接到互联网,并在前两列(URL、日期)中填写了 URL 列表及其上传日期

使用另一种方法,我需要使用包含每个文件的特定路径的字符串数组填充第三列(DestinationFile)。字符串数组的大小与 DataTable 的行数相同。

是否可以用字符串数组填充 DataTable 的第三列(在这种情况下,但可以是任何类型)?

【问题讨论】:

    标签: c# arrays list datatable ado.net


    【解决方案1】:

    没有办法do it directly in one step,因此您必须使用数据表的Rows 集合和DataRowindexer 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;

    【讨论】:

    • 谢谢,问题解决了。太糟糕了,没有直接的方法来加载列!
    猜你喜欢
    • 1970-01-01
    • 2018-12-17
    • 2012-11-13
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 2023-01-17
    相关资源
    最近更新 更多