2016-11-03 2 views
0

문제 : 개체 목록 (aTSource)에는 공백이있는 필드 이름 목록과 밑줄이 없으므로 변수에 일치하지 않습니다.T 목록에서 공백과 밑줄 제거

나는 내 Model 클래스의 T 개체 목록이 있습니다. 이 목록에는 필드 이름, 값 및 필드 유형이 포함됩니다. 나는 필드 이름에 들어가서 이름에서 공백과 밑줄을 제거하고 싶다.

이 코드의 목적은 Excel 문서와 WPF 양식의 필드를 비교하여 공통으로 해당 필드 이름의 목록을 반환하는 것입니다. aTSource에서

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); 
     list.Add(aTSource); 
    } 
} 

샘플 값 : 당신의 목표는 단지 ​​공백 및 밑줄의 독립적 인 두 개의 문자열을 비교하는 경우

IP_Address  null string 
Product Name null string 

답변

0

필드 이름이 모두 일치하는지 확인하기 위해 Excel 필드 이름 목록의 첫 번째 필드 이름과 WPF 양식 필드 이름의 두 번째 필드를 대체 문을 사용하여 두 개의 Foreach 루프를 만듭니다.

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

, 당신이 그들을 제거 할 확장 메서드를 만들 수 있습니다 후 비교합니까 :

public static string SuperStrip(this string InputString) 
{ 
    if (string.IsNullOrWhiteSpace(InputString)) 
     return string.Empty; 

    return InputString.Replace(" ", string.Empty).Replace("_", string.Empty); 
} 

이러한 식의 각각은 다음 true 상태를 초래 :

물론
bool foo; 
foo = "nicekitty".SuperStrip() == "nice kitty".SuperStrip(); 
foo = "nicekitty".SuperStrip() == "nice_kitty".SuperStrip(); 
foo = "nice_kitty".SuperStrip() == "nice kitty".SuperStrip(); 

, 당신은 또한 그들을 비교하는 하나의 함수에서 그 래핑 수 :

public static bool HeaderCompare(string String1, string String2) 
{ 
    if (string.IsNullOrWhiteSpace(String1)) 
     String1 = string.Empty; 
    if (string.IsNullOrWhiteSpace(String2)) 
     String2 = string.Empty; 

    return String1.Replace(" ", string.Empty).Replace("_", string.Empty) == 
     String2.Replace(" ", string.Empty).Replace("_", string.Empty); 
} 

을이 거의 과도하게 단순화 보인다, 그것이 내가 떨어져있어 경우에 주시기 그래서, 당신의 작업을 오해 할 수 그래서 저에게 알려주세요.

+0

그러나 제안에 감사드립니다. 그러나 T 목록의 필드 이름을 변경하는 방법을 찾고있었습니다. "IP_Address"는 "IPAddress"가되고 "Product Name"은 "ProductName"이됩니다. 밑줄과 공백을 다른 문자 "^"로 바꾸고이 새로운 문자를 비교하여이 문제를 해결했습니다. – Kahlan