static public DataSetTypeMap GetDataSetTypeMap(Type type) { lock (DataSetTypeMaps) { // add to cache to avoid recreating type properties via .NET Reflection if (DataSetTypeMaps.ContainsKey(type)) { return(DataSetTypeMaps[type]); } DataSetTypeMap dataTypeMap = new DataSetTypeMap() { ElementType = type, Properties = new List <DataSetTypeMapProperty>() }; foreach (PropertyInfo property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty)) { // avoid indexers if (property.GetIndexParameters().Length > 0) { continue; } dataTypeMap.Properties.Add(new DataSetTypeMapProperty() { Property = property, DataType = GetBestAllowableTableType(property.PropertyType) }); } DataSetTypeMaps.Add(type, dataTypeMap); return(dataTypeMap); } }
static public DataSet PopulateDataSet(params IEnumerable[] enumerables) { // 4/13/14 MRC - added check for null enumerables if (enumerables == null || enumerables.Length == 0) { return(new DataSet("Empty")); } HashSet <string> tableNames = new HashSet <string>(); DataSet ds = new DataSet(); try { Int32 idx = 0; foreach (IEnumerable enumerable in enumerables) { Type dictionarykeyType = null; Object[] dictionaryKeys = null; Boolean isDictionary = (enumerable is IDictionary); if (isDictionary) { IDictionary dictionary = enumerable as IDictionary; dictionarykeyType = GetBestAllowableTableType((dictionary.Keys as IEnumerable).AsQueryable().ElementType); dictionaryKeys = new Object[dictionary.Keys.Count]; dictionary.Keys.CopyTo(dictionaryKeys, 0); } IEnumerable items = isDictionary ? (enumerable as IDictionary).Values : enumerable; Type elementType = items.AsQueryable().ElementType; DataSetTypeMap typeMap = GetDataSetTypeMap(elementType); if (typeMap.Properties.Count == 0) { continue; } if (idx++ == 0) { // this is the first item ds.DataSetName = items.AsQueryable().ElementType.Name; } // ensure that table names are unique Int32 nameIdx = 2; string tableName = elementType.Name; do { if (tableNames.Contains(tableName)) { tableName = string.Format("{0} ({1})", elementType.Name, nameIdx++); continue; } tableNames.Add(tableName); break; } while (true); // create the table and it's columns DataTable table = ds.Tables.Add(tableName); if (isDictionary) { table.Columns.Add("Key", dictionarykeyType); } foreach (DataSetTypeMapProperty typeProperty in typeMap.Properties) { table.Columns.Add(typeProperty.Property.Name, typeProperty.DataType); } // now fill the rows for this table Int32 itemIdx = 0; Int32 valueOffSet = isDictionary ? 1 : 0; foreach (var item in items) { if (item != null) { Object[] values = new Object[table.Columns.Count]; if (isDictionary) { values[0] = dictionarykeyType == typeof(String) ? dictionaryKeys[itemIdx].ToString() : dictionaryKeys[itemIdx]; } for (Int32 i = 0; i < typeMap.Properties.Count; i++) { values[i + valueOffSet] = typeMap.Properties[i].Property.GetValue(item, null); } table.Rows.Add(values); } itemIdx++; } } return(ds); } catch (Exception) { ds.Dispose(); throw; } }