To run, refactoring logic into a function.
_gridModel.Header = AppendItem(_gridModel.Header, item == null ? null : item.Header); _gridModel.Width = AppendItem(_gridModel.Width, item == null ? null : item.Width); ... ... string AppendItem(string src, string item) { if (! string.IsNullOrEmpty(src)) src += ","; if (! string.IsNullOrEmpty(item)) src += item; return src; }
A good next step would be to use reflection and properties:
Edit: The configured reflection solution did not actually debug it yet.
AppendProperties(_gridModel, item, "Header", "Width", "Align", ...) void AppendProperty(object gridmodel, object item, params string[] propNames) { foreach (string propName in propNames) AppendProperties(gridmodel, item, propName); } void AppendProperties(object gridmodel, object item, string propName) { PropertyInfo piGrid = gridmodel.GetType().GetProperty(propName); if (piGrid != null && piGrid.PropertyType == typeof(string)) { piGrid.SetValue(gridmodel, piGrid.GetValue(gridmodel, null).ToString() + ",", null); } if (item == null) return; PropertyInfo piItem = item.GetType().GetProperty(propName); if (piItem != null) { piGrid.SetValue(gridmodel, piGrid.GetValue(gridmodel, null).ToString() + piItem.GetValue(item, null).ToString(), null); } }
source share