2016-08-11 35 views
-1
private void add_value_to_row(client_file client_file, ref StringBuilder OutputCustomer, String value) 
{ 
    if (client_file.output_format == "txt") 
     if (value = "the first value in add_value_to_row") 
     OutputCustomer.AppendFormat("{0}", value); 
     else if (value = "every other value in add_value_to_row") 
     OutputCustomer.AppendFormat("\t{0}", value); 
} 

我有一個上面寫的函數,它根據下面的代碼從「x」獲取輸入並以.txt格式創建數據行。我想知道如何編寫嵌套的if語句,以便它執行用引號引起來的內容?根據以下數據的最終輸出應該輸出OutputCustomer.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}", x.url, x.company, x.Country, x.vendor, x.product);StringBuilder的格式結構

OutputCustomer = new StringBuilder(); 

add_value_to_row(clientInfo.cf, ref OutputCustomer, x.url); 
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.company); 
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.Country); 
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.vendor); 
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.product); 
+1

現在還不清楚你在這裏究竟在問什麼? – Rahul

+0

很難理解「第一個值add_value_to_row」的意圖,因爲「add_value_to_row」似乎是一種方法而不是集合。你是說你想讓方法猜測你通過了哪個屬性?順便說一句,'StringBuilder'是一個類,而不是一個結構。沒有必要通過'ref' –

回答

0

爲什麼要逐個添加項目?給你的對象的方法,讓它決定。

private void add_value_to_row(client_file client_file, ref StringBuilder OutputCustomer, YourType value) 
{ 
    if (client_file.output_format == "txt") 

    OutputCustomer.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}", 
    value.url,value.company,value.Country,value.vendor,value.product); 

} 

,並調用它像這樣

add_value_to_row(clientInfo.cf, ref OutputCustomer, x); 

否則你必須給一個布爾或詮釋的方法signiture

更新

如果你真的想你方法它是你需要一個布爾在簽名的方式

private void add_value_to_row(client_file client_file, ref StringBuilder OutputCustomer, String value, bool isFirst=false) 
{ 
    if (client_file.output_format == "txt") 
     if (isFirst) 
     OutputCustomer.AppendFormat("{0}", value); 
     else 
     OutputCustomer.AppendFormat("\t{0}", value); 
} 

,並調用它像這樣

add_value_to_row(clientInfo.cf, ref OutputCustomer, x.url, true); 
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.company); 
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.Country); 
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.vendor); 
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.product); 

另外要注意的是,你可以把它作爲一個可選的參數,所以你不需要它每次寫

+0

我只寫了5個條目來簡化示例,但實際代碼中實際上有很多。我只需要編寫if語句,以便第一項格式爲{0},然後其餘爲\ t {0} –

+0

@LucasHan檢查更新 –

+0

謝謝,那就是我一直在尋找的! –

0

它看起來像你想創建制表符分隔的輸出行。更簡單的方法是:

string outputCustomer = string.Join("\t", new {x.url, x.company, x.Country, x.vendor, x.product}); 

參見String.Join