.NET - Convert Generic Collection to DataTable

前端 未结 5 1702
感情败类
感情败类 2020-11-27 10:17

I am trying to convert a generic collection (List) to a DataTable. I found the following code to help me do this:

// Sorry about indentation
public class Col         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 10:46

    Then presumably you'll need to lift them to the non-nullable form, using Nullable.GetUnderlyingType, and perhaps change a few null values to DbNull.Value...

    Change the assignment to be:

    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
    

    and when adding the columns to be:

    table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(
                prop.PropertyType) ?? prop.PropertyType);
    

    And it works. (?? is the null-coalescing operator; it uses the first operand if it is non-null, else the second operand is evaluated and used)

提交回复
热议问题