1. 程式人生 > >C# 實體轉換為DataTable

C# 實體轉換為DataTable

    //AGroupCondition:實體型別
            DataTable dt = new DataTable();


            Type elementType = typeof(AGroupCondition);


            elementType.GetProperties().ToList().ForEach(propInfo => dt.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
            foreach (AGroupCondition item in lstCondition)
            {
                DataRow row = dt.NewRow();
                elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
                dt.Rows.Add(row);
            }