How to reorganize this code?

how can i reorganize this code to one method or something else?

if (!string.IsNullOrEmpty(_gridModel.Header)) _gridModel.Header += ","; if (item != null) _gridModel.Header += item.Header; if (!string.IsNullOrEmpty(_gridModel.Width)) _gridModel.Width += ","; if (item != null) _gridModel.Width += item.Width; if (!string.IsNullOrEmpty(_gridModel.Align)) _gridModel.Align += ","; if (item != null) _gridModel.Align += item.Align; if (!string.IsNullOrEmpty(_gridModel.Filter)) _gridModel.Filter += ","; if (item != null) _gridModel.Filter += item.Filter; if (!string.IsNullOrEmpty(_gridModel.Type)) _gridModel.Type += ","; if (item != null) _gridModel.Type += item.Type; if (!string.IsNullOrEmpty(_gridModel.Sort)) _gridModel.Sort += ","; if (item != null) _gridModel.Sort += item.Sort; 
+4
source share
2 answers

Assuming you have .NET 3.5:

 string Filter(string input, SomeType item, Func<SomeType, string> extract) { if (!String.IsNullOrEmpty(input)) { if (item == null) return ","; else return "," + extract(item); } } _gridModel.Header += Filter(_gridModel.Header, item, i => i.Header); _gridModel.Width += Filter(_gridModel.Width, item, i => i.Width); _gridModel.Align += Filter(_gridModel.Align, item, i => i.Align); // etc... 
+7
source

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); } } 
+15
source

All Articles