2016-07-31 166 views
3

在我使用的信息系統(SAP Business One)中,每個文檔都在SQL表中表示。C# - 常量字符串字典

例如:

客戶訂單文檔:ORDR

發票憑證:OINV

採購報價單:OPRQ

等等

用戶點擊,當上一個的按鈕,我需要使用一個存在的函數來檢查一部分SQL表,並檢查這個客戶端是否有系統中的文檔。 該函數返回一個字符串消息,其中包含表示此客戶機在系統中具有的文檔的表的名稱。

我需要編寫一個函數來替換表名與文檔名稱。

eample:

"Client with ID:5634 has documents: OINV, ORDR" 

需要被替換

"Client with ID:5634 has documents: Invoice, Client order" 

我猜應該使用字符串字典。怎麼做?

感謝

+0

的可能的複製[C#字符串替換字典(http://stackoverflow.com/questions/1231768/c-sharp -string-replace-with-dictionary) – NikolayKondratyev

+0

是否需要定製而不需要重新編譯? –

+0

您是否確實有需要替換的文本,或者您是否生成了「帶ID的客戶端:5634有文檔:OINV,ORDR」? –

回答

1

使用字典和LINQ:

var str2 = new StringBuilder(str); 

foreach (var pair in databases) { 
    str2.Replace(pair.Key, pair.Value); 
} 

var newstr = str2.ToString(); 
5

理想情況下,你不應該做字符串:

var databases = new Dictionary<string, string>(); 

databases["OINV"] = "Invoice"; 
databases["OPRQ"] = "Purchase Quotation"; 
databases["ORDR"] = "Order"; 
// ... 

var str = "Some random text ORDR more text ORDR text OPRQ text OINV text ORDR"; 

var newstr = databases.Aggregate(str, (current, value) => 
    current.Replace(value.Key, value.Value)); 

後者還可以,一旦你創建了詞典使用用生成的字符串替換 - 而是從翻譯的字符串生成它。因此,例如 - 不知道你實際上已經得到了什麼樣的代碼 - 你可以有:

private static readonly Dictionary<string, string> TableNameTranslations 
    = new Dictionary<string, string> 
{ 
    { "ORDR", "Client order document" }, 
    { "OINV", "Invoice document" }, 
    { "OPRQ", "Purchase quotation" } 
}; 

... 

public string GetClientDocumentDisplayString(int clientId) 
{ 
    var tableNames = GetTableNamesForClient(clientId); 
    var translatedNames = tableNames.Select(t => TableNameTranslations[t]); 
    return $"Client with ID:{clientId} has documents: {string.Join(",", translatedNames)}"; 
} 

private IList<string> GetTableNamesForClient(int clientId) 
{ 
    // Whatever your code needs, returning ORDR, OINV etc 
}