2017-02-25 30 views
0

我硬編碼,我肯定可以更巧妙地做了的所有成員 - 有趣的小問題 - 使用C#6.0CONCAT類

如何減少這一點 - 它會在另一個20線。

string fullLine = newLine.col1_index_no + 
      newLine.col2_depot_custRef + 
      newLine.col3_depot_no + 
      newLine.col4_driver_id + 
      newLine.col5_vehicle_id + 
      newLine.col6_trans_type; 

如果它幫助這裏是類:

class lineBuilder 
{ 
    public string col1_index_no { get; set; } 
    public string col2_depot_custRef { get; set; } 
    public string col3_depot_no { get; set; } 
    public string col4_driver_id { get; set; } 
    public string col5_vehicle_id { get; set; } 
    public string col6_trans_type { get; set; } 
    public string col7_sign_id { get; set; } 
    public string col8_note_id { get; set; } 
    public string col9_route_code { get; set; } 
    public string col10_RA_no { get; set; } 
    public string col11_doc_type { get; set; } 
    public string col12_user_gen_flag { get; set; } 
    public string col13_seq_no { get; set; } 
    public string col14_pallet_id { get; set; } 
    public string col15_tote_id { get; set; } 
    public string col16_adj_type { get; set; } 
    public string col17_rtn_sig_not_avlb { get; set; } 
    public string col18_scan_dateTime { get; set; } 
    public string col19_scan_in_time { get; set; } 
    public string col20_AX_status { get; set; } 

} 
+0

您可以使用反射並遍歷屬性來獲取它們的值並創建字符串。訣竅在於得到你想要的訂單 – Nkosi

回答

1

您可以通過反射做到這一點。此示例代碼將打印出所有屬性的按字母順序排列:

var lb = new lineBuilder 
{ 
    col1_index_no = "item one", 
    col2_depot_custRef = "item depot custRef" 
    col10_RA_no = "further values will not make this explanation any clearer" 
}; 

StringBuilder sb = new StringBuilder(); 
IEnumerable<PropertyInfo> properties = typeof(lineBuilder) 
              .GetProperties() 
              .Where(p => p.PropertyType.Equals(typeof(string))) 
              .OrderBy(p => p.Name); 

foreach(PropertyInfo propertyInfo in properties) 
{ 
    var value = (string)propertyInfo.GetValue(lb); 
    sb.AppendLine(string.Format("{0}: {1}", propertyInfo.Name, value ?? String.Empty)); 
} 

Console.WriteLine(sb.ToString()); 

然而,你不希望他們以字母順序,你希望他們在數字順序。

您需要不同的OrderBy子句。

如果您的所有屬性名稱都採用格式col{number},則可以使用正則表達式從每個名稱中提取數字並使用它來執行您的排序。

Regex regex = new Regex(@"^col(\d+)"); 

IEnumerable<PropertyInfo> properties = typeof(lineBuilder) 
              .GetProperties() 
            .Where(p => p.PropertyType.Equals(typeof(string))) 
            .OrderBy(p => int.Parse(regex.Match(p.Name).Groups[1].Value)); 
+0

我知道它會與反思有關,我只是無法擺脫它。感謝您加入我的竅門,我會玩這個安德魯...我總是忘記正則表達式格式.... –