2017-02-25 43 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

我知道它会与反思有关,我只是无法摆脱它。感谢您加入我的窍门,我会玩这个安德鲁...我总是忘记正则表达式格式.... –