Convert Collection to DataSet
Freitag, 21. August 2009 | Autor: admin
Heute hatte ich das Problem aus einer Collection ein DataSet zu erzeugen. Folgender Beitrag war dabei sehr hilfreich:
Den dort vorgestellten Code, habe ich noch etwas verfeinert und leicht angepasst:
/// <summary> /// This will take anything that implements the ICollection interface and convert /// it to a DataSet. /// </summary> /// <example> /// CollectiontoDataSet<CollectionType> converter = new CollectionToDataSet<CollectionType>(collection); /// DataSet ds = converter.CreateDataSet("dataSetName", "dataTableName"); /// </example> /// <typeparam name="T"></typeparam> public class CollectionToDataSet<T> where T : System.Collections.ICollection { T _collection; /// <summary> /// Initializes a new instance of the <see cref="CollectionToDataSet<T>"/> class. /// </summary> /// <param name="list">The list.</param> public CollectionToDataSet(T list) { _collection = list; } #region Properties private string _dataTableName = String.Empty; private PropertyInfo[] _propertyCollection = null; private PropertyInfo[] PropertyCollection { get { if (_propertyCollection == null) { _propertyCollection = GetPropertyCollection(); } return _propertyCollection; } } #endregion /// <summary> /// Gets the property collection. /// </summary> /// <returns></returns> private PropertyInfo[] GetPropertyCollection() { if (_collection.Count > 0) { IEnumerator enumerator = _collection.GetEnumerator(); enumerator.MoveNext(); return enumerator.Current.GetType().GetProperties(); } return null; } /// <summary> /// Fills the data table. /// </summary> /// <returns></returns> private DataTable FillDataTable() { IEnumerator enumerator = _collection.GetEnumerator(); DataTable dt = CreateDataTable(); while (enumerator.MoveNext()) { dt.Rows.Add(FillDataRow(dt.NewRow(), enumerator.Current)); } return dt; } /// <summary> /// Fills the data row. /// </summary> /// <param name="dataRow">The data row.</param> /// <param name="p">The p.</param> /// <returns></returns> private DataRow FillDataRow(DataRow dataRow, object p) { foreach (PropertyInfo property in PropertyCollection) { dataRow[property.Name.ToString()] = property.GetValue(p, null); } return dataRow; } /// <summary> /// Creates the data table. /// </summary> /// <returns></returns> private DataTable CreateDataTable() { DataTable dt = new DataTable(_dataTableName); foreach (PropertyInfo property in PropertyCollection) { dt.Columns.Add(property.Name.ToString()); } return dt; } /// <summary> /// Creates the data set. /// </summary> /// <param name="dataSetName">Name of the data set.</param> /// <param name="dataTableName">Name of the data table.</param> /// <returns>DataSet</returns> public DataSet CreateDataSet(string dataSetName, string dataTableName) { _dataTableName = dataTableName; DataSet ds = new DataSet(dataSetName); ds.Tables.Add(FillDataTable()); return ds; } }
Thema: .NET > 3.0, C# | Beitrag kommentieren


