2010-01-30 86 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