【发布时间】:2011-01-11 07:13:15
【问题描述】:
为了将 Linq 转换为 DataTable,我使用以下扩展方法(取自 Stackoverflow)
Linq 到数据表
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;
}
WriteXml
PersonDB.PersonDataContext con = new PersonDB.PersonDataContext();
DataTable tb = new DataTable();
tb = con.Persons.ToDataTable();
tb.WriteXml(@"d:\temp\Person.xml");
问题
扩展方法创建 XML 文件,但对于空值,不会在 XML 文件中创建任何元素。它表示如果 Commission 字段为 null,则 Xml 生成中缺少 Commission 元素。
我想为空值(参考类型)和 (0.00) 为小数和 (0) 为整数插入带有空字符串的元素。我需要在哪里进行更改?
【问题讨论】:
标签: asp.net xml linq reflection datatable