2010-01-30 81 views
3

我有要求将LINQ转换为DataTable。Linq to DataSet - 处理空值

我从StackOverflow上偷了以下扩展方法:

public static DataTable ToDataTable<T>(this IEnumerable<T> items) 
     { 
      var tb = new DataTable(typeof(T).Name); 
      PropertyInfo[] props = 
      typeof(T).GetProperties(BindingFlags.Public 
            | BindingFlags.Instance); 

      foreach (var prop in props) 
      { 
       tb.Columns.Add(prop.Name, prop.PropertyType); 
      } 

      foreach (var item in items) 
      { 
       var values = new object[props.Length]; 
       for (var i = 0; i < props.Length; i++) 
       { 
        values[i] = props[i].GetValue(item, null); 
       } 

       tb.Rows.Add(values); 
      } 
      return tb; 
    } 

当表包含空值会抛出异常。 (即)

DataSet does not support System.Nullable<> 

Comission(十进制类型)列包含空值)

tb.Columns.Add(prop.Name, prop.PropertyType); 

如何解决呢?

回答

3

这里有一个拉皮条的版本:

public static DataTable ToDataTable<T>(this IEnumerable<T> items) { 
    DataTable table = new DataTable(typeof(T).Name); 
    PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 

    foreach (var prop in props) { 
     Type propType = prop.PropertyType; 

     // Is it a nullable type? Get the underlying type 
     if (propType.IsGenericType && propType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) 
      propType = new NullableConverter(propType).UnderlyingType; 

     table.Columns.Add(prop.Name, propType); 
    } 

    foreach (var item in items) { 
     var values = new object[props.Length]; 
     for (var i = 0; i < props.Length; i++) 
      values[i] = props[i].GetValue(item, null); 

     table.Rows.Add(values); 
    } 

    return table; 
} 

编辑:修改我的代码了一下,测试它,它的工作原理! :)

+0

非常感谢 – Dhina 2010-01-30 20:10:36

0

您可以检查空值,然后将DBNull.Value作为值存储。有一个MSDN article about null values,它特别声明Datasets对Nullable的支持不足。

如果你有

values[i] = props[i].GetValue(item, null); 

使其

var value = props[i].GetValue(item, null); 
values[i] = value ?? ((object)DBNull.Value); 
+1

你也可以使用可为空的操作符??所以代码将是'values [i] = value ?? (object)DBNull.Value;' – 2010-01-30 20:08:31

+0

非常感谢你 – Dhina 2010-01-30 20:15:16

+0

@Scott:很好的通话。我更新了它。 – TheDon 2010-01-30 21:00:19