Reputation: 402
the interpolated string is easy, just a string lead with $ sign. But what if the string template is coming from outside of your code. For example assume you have a XML file containing following line:
<filePath from="C:\data\settle{date}.csv" to="D:\data\settle{date}.csv"/>
Then you can use LINQ to XML read the content of the attributes in.
//assume the ele is the node <filePath></filePath>
string pathFrom = ele.Attribute("from").value;
string pathTo = ele.Attibute("to").value;
string date = DateTime.Today.ToString("MMddyyyy");
Now how can I inject the date
into the pathFrom
variable and pathTo
variable?
If I have the control of the string itself, things are easy. I can just do var xxx=$"C:\data\settle{date}.csv";
But now, what I have is only the variable that I know contains the placeholder date
Upvotes: 4
Views: 4369
Reputation: 64
know Its a little old thread, but came up with a similar problem and needed to interpolate with object property values with a string. Hope this helps someone. Used Sring.Split() , Reflection and String.Concat()
public class test
{
public string Name { get; set; }
public string Designation { get; set; }
public string Company { get; set; }
}
var Obj = new test();
a.Name = "Vidura";
a.Designation = "Lead Engineer";
a.Company = "Inivos Global";
string Str = "My Name is #<Name># and im a #<Designation># at #<Company># ";
var Arr = Str.Split('#').ToArray();
for (int i = 0; i < Arr.Length - 1; i++)
{
if (Arr[i].StartsWith("<") && Arr[i].EndsWith(">"))
{
Arr[i] = Obj.GetType().GetProperty(Arr[i].Substring(1, Arr[i].Length - 2)).GetValue(Obj).ToString();
}
}
var newStr = String.Concat(Arr);
MessageBox.Show(newStr);
Output Will be
My Name is Vidura and im a Lead Engineer at Inivos Global
Upvotes: 0
Reputation: 438
If you treat your original string as a user-input string (or anything that is not processed by the compiler to replace the placeholder, then the question is simple - just use String.Replace()
to replace the placehoder {date}
, with the value of the date as you wish. Now the followup question is: are you sure that the compiler is not substituting it during compile time, and leaving it untouched for handling at the runtime?
Upvotes: 1
Reputation: 12032
String interpolation is a compiler feature, so it cannot be used at runtime. This should be clear from the fact that the names of the variables in the scope will in general not be availabe at runtime.
So you will have to roll your own replacement mechanism. It depends on your exact requirements what is best here.
If you only have one (or very few replacements), just do
output = input.Replace("{date}", date);
If the possible replacements are a long list, it might be better to use
output = Regex.Replace(input, @"\{\w+?\}",
match => GetValue(match.Value));
with
string GetValue(string variable)
{
switch (variable)
{
case "{date}":
return DateTime.Today.ToString("MMddyyyy");
default:
return "";
}
}
If you can get an IDictionary<string, string> mapping variable names to values you may simplify this to
output = Regex.Replace(input, @"\{\w+?\}",
match => replacements[match.Value.Substring(1, match.Value.Length-2)]);
Upvotes: 6
Reputation: 2809
SOLUTION 1:
If you have the ability to change something on xml template change {date} to {0}.
<filePath from="C:\data\settle{0}.csv" to="D:\data\settle{0}.csv" />
Then you can set the value of that like this.
var elementString = string.Format(element.ToString(), DateTime.Now.ToString("MMddyyyy"));
Output: <filePath from="C:\data\settle08092020.csv" to="D:\data\settle08092020.csv" />
SOLUTION 2:
If you can't change the xml template, then this might be my personal course to go.
<filePath from="C:\data\settle{date}.csv" to="D:\data\settle{date}.csv" />
Set the placeholder like this.
element.Attribute("to").Value = element.Attribute("to").Value.Replace("{date}", DateTime.Now.ToString("MMddyyyy"));
element.Attribute("from").Value = element.Attribute("from").Value.Replace("{date}", DateTime.Now.ToString("MMddyyyy"));
Output: <filePath from="C:\data\settle08092020.csv" to="D:\data\settle08092020.csv" />
I hope it helps. Kind regards.
Upvotes: 1
Reputation: 11
String interpolation allows the developer to combine variables and text to form a string.
Example Two int variables are created: foo and bar.
int foo = 34;
int bar = 42;
string resultString = $"The foo is {foo}, and the bar is {bar}.";
Console.WriteLine(resultString);
Output:
The foo is 34, and the bar is 42.
Upvotes: -7
Reputation: 74730
You can't directly; the compiler turns your:
string world = "world";
var hw = $"Hello {world}"
Into something like:
string world = "world";
var hw = string.Format("Hello {0}", world);
(It chooses concat, format or formattablestring depending on the situation)
You could engage in a similar process yourself, by replacing "{date" with "{0" and putting the date as the second argument to a string format, etc.
Upvotes: 1