General method accepting List <T>
I have 5 classes that are a data grid row. All of these classes inherit from the abstract CoreGrid class.
I have an export mechanism that uses reflection to determine the columns to export. At this point, I have a method for each type of grid (ExportOrganisations, ExportPeople, ExportEvents), but this is terrible, since the only difference between them is the part in which it searches for the type. A sample code is shown below:
public string ExportEvents(List<EventGrid> events) { DataTable report = new DataTable(); EventGrid ev = new EventGrid(); Type t = ev.GetType(); PropertyInfo[] props = t.GetProperties(); foreach (PropertyInfo prop in props) { if (!prop.Name.Contains("ID")) { report.Columns.Add(prop.Name); } } foreach (var item in events) { DataRow dr = report.NewRow(); Type itemType = item.GetType(); PropertyInfo[] itemProps = itemType.GetProperties(); foreach (PropertyInfo prop in itemProps) { if (report.Columns.Contains(prop.Name)) { if (prop.GetValue(item, null) != null) { dr[prop.Name] = prop.GetValue(item, null).ToString().Replace(",", string.Empty); } } } report.Rows.Add(dr); } return GenerateCSVExport(report, ExportType.Events); }
My question is: how would I condense these methods into one method when the method accepts a list that inherits from CoreGrid?
There must be something like this. Due to the ability to infer types, you do not need to change the current call signatures, just point everything to the general method:
//if myList is a list of CoreGrid or derived. string export = ExportEvents(myList); public string ExportEvents<T>(List<T> events) where T : CoreGrid { DataTable report = new DataTable(); Type t = typeof(T); PropertyInfo[] props = t.GetProperties(); foreach (PropertyInfo prop in props) { if (!prop.Name.Contains("ID")) { report.Columns.Add(prop.Name); } } foreach (var item in events) { DataRow dr = report.NewRow(); Type itemType = item.GetType(); PropertyInfo[] itemProps = itemType.GetProperties(); foreach (PropertyInfo prop in itemProps) { if (report.Columns.Contains(prop.Name)) { var propValue = prop.GetValue(item, null) if (propValue != null) { dr[prop.Name] = propValue.ToString().Replace(",", string.Empty); } } } report.Rows.Add(dr); } return GenerateCSVExport(report, ExportType.Events); }