Kahlan Kahlan - 3 months ago 34
C# Question

Remove spaces and underscores from a T List

A T list of object (aTSource) contains a list of field names with extra spaces and underscores preventing matches to a variable without.

I have a T list of object from my Model class. This list includes a Field name, value and the field type. I want to go into the field names and remove any spaces and underscores from the name.

The purpose of the code is to compare fields from an Excel document and WPF form and return a list of those field names in common.

foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
T aTSource = new T();
foreach (PropInfo aField in commonFields)
PropertyInfo propertyInfos = aTSource.GetType().GetProperty(aField.Name);
var value = (dataRow[afield.Name] == DBNull.Value) ? null : dataRow[afield.Name];
propertyInfos.SetValue(aTSource, value, null);

Sample values from aTSource:

IP_Address null string
Product Name null string


Create two Foreach loops with replacement statements, the first for the list of Excel field names and the second for the WPF form of field names, to ensure that the field names both match.

foreach (DataColumn column in dataTable.Columns)
column.ColumnName = column.ColumnName.Replace(" ", "");
column.ColumnName = column.ColumnName.Replace("_", "");