I have the following function to replace all the occurrence of a string that matches certain token.
public string ReplaceTokenBySample(string StingValue)
{
List<Token> tokens = GetTokenList();
foreach (var token in tokens)
{
StingValue = StingValue.Replace(token.Token, token.SampleValue);
}
return StingValue;
}
GetTokenList(); will return
Token SampleValue
##Username## John Doe
##UserEmail## [email protected]
##UserFirstName## John
##UserLastName## Doe
How can I optimize this code?
Full console app code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Token
{
public string TokenValue { get; set; }
public string SampleValue { get; set; }
}
public class Program
{
public List<Token>GetTokenList()
{
List<Token> tokens = new List<Token>
{
new Token(){ TokenValue = "##Username##", SampleValue="John Doe" },
new Token(){ TokenValue = "##UserEmail##", SampleValue="[email protected] " },
new Token(){ TokenValue = "##UserFirstName##", SampleValue="John" },
new Token(){ TokenValue = "##UserLastName##", SampleValue="Doe"}
};
return tokens;
}
public string ReplaceTokenBySample(string StringValue)
{
List<Token> tokens = GetTokenList();
foreach (var token in tokens)
{
StringValue = StringValue.Replace(token.TokenValue, token.SampleValue);
}
return StringValue;
}
public static void Main(string[] args)
{
Program obj = new Program();
string StringValue ="Hello ##Username##! I have emailed you at ##UserEmail##. ##UserFirstName## ##UserLastName## how is you days going on. Have a good day ##Username##. ";
Console.WriteLine(obj.ReplaceTokenBySample(StringValue));
}
}
}
ReplaceTokenBySampledoesn't allow you to pass in your own tokens? \$\endgroup\$GetTokenList, thenReplaceTokenBySampleis limited to always use whatever tokens are returned byGetTokenList. If, instead, you pass tokens in as an argument, then you can reuse the replacement logic in different contexts. \$\endgroup\$