3

In the information system that i am working with (SAP Business One), every document is represented in an SQL table.

Client order document : ORDR

Invoice document : OINV

Purchase Quotation : OPRQ

when the user clicks on one of the buttons, i need to use a exist function that checks in a part of the SQL tables, and checks if this client has documents in the system. the function returns a string message with the names of the tables that represent the documents this client has in the system.

i need to write a function that will replace the table names with the documents names.

eample:

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

needs to be replace with

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

I guess should use a string dictionary. How to do it?

thanks

Suncatcher
  • 10,355
  • 10
  • 52
  • 90
Zag Gol
  • 1,038
  • 1
  • 18
  • 43
  • Possible duplicate of [C# String replace with dictionary](http://stackoverflow.com/questions/1231768/c-sharp-string-replace-with-dictionary) – Nikolay K Jul 31 '16 at 07:59
  • Does it need to be customizable without recompiling ? – Florian F. Jul 31 '16 at 08:00
  • Do you actually have the text that needs to be replaced, or are you generating "Client with ID:5634 has documents: OINV, ORDR"? – Jon Skeet Jul 31 '16 at 08:22

2 Answers2

6

Ideally you shouldn't be doing string replacement with the generated string - instead, generate it from the translated strings. So for example - without knowing what code you've actually got - you could have:

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
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Using a dictionary and Linq:

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));

The latter can also be used once you have created your Dictionary:

var str2 = new StringBuilder(str);

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

var newstr = str2.ToString();
Heinzi
  • 167,459
  • 57
  • 363
  • 519
pie3636
  • 795
  • 17
  • 31