views:

122

answers:

1

For coonverting Linq to DataTable I am using the following Extension Method(Taken from Stackoverflow)

Linq to DataTable

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");

Question


The Extension Method creates XML file.But for null values no element is created in XML file.Say if Commission field is null then commission element is missing in Xml generation. I want to insert element with empty string for null values (ref type) and (0.00) for decimals and (0) for integers. where do i need to make change?

A: 

I would create an extension method for DataTable which does that:

public static DataTable ZeroNullValues(this DataTable dataTable)
{
    foreach(DataRow row in dataTable.Rows)
    {
        for(int i=0;i<dataTable.Columns.Count;i++)
        {
            if(row[i] == null)
            {
                Type columnType = dataTable.Columns[i].DataType;
                if(columnType == typeof(string))
                {
                    row[i] = string.Empty;
                }
                else if(columnType == typeof(int) || columnType == typeof(long))
                {
                    row[i] = 0;
                }
                else if(columnType == typeof(float) || columnType == typeof(double))
                {
                    row[i] = 0.00F;
                }
            }
        }
    }
    return dataTable;
}
Rex M