Format string with dictionary in C#

Suppose I had the following code in Python (yes, this question is about c# this is just an example)

string = "{entry1} {entry2} this is a string"
dictionary = {"entry1": "foo", "entry2": "bar"}

print(string.format(**dictionary))

# output is "foo bar this is just a string"

In this string, it would replace the {entry1} and {entry2} from the string to foo and bar using the .format()

Is there anyway I can replicate this EXACT same thing in C# (and also remove the curly braces) like the following code:

string str1 = "{entry1} {entry2} this a string";
Dictionary<string, string> dict1 = new() {
    {"entry1", "foo"},
    {"entry2", "bar"}
};

// how would I format this string using the given dict and get the same output?

You can write an extension method for a dictionary and in it manipulate your string as per your need Like

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;


public static class DictionaryExtensions
{
    public static string ReplaceKeyInString(this Dictionary<string, string> dictionary, string inputString)
    {

        var regex = new Regex("{(.*?)}");
        var matches = regex.Matches(inputString);
        foreach (Match match in matches)
        {
            var valueWithoutBrackets = match.Groups[1].Value;
            var valueWithBrackets = match.Value;

            if(dictionary.ContainsKey(valueWithoutBrackets))
                inputString = inputString.Replace(valueWithBrackets, dictionary[valueWithoutBrackets]);
        }

        return inputString;
    }
}

Now use this extension method to convert given string to the expected string,

string input = "{entry1} {entry2} this is a string";
Dictionary<string, string> dictionary = new Dictionary<string, string> 
{ 
  { "entry1", "foo" }, 
  { "entry2", "bar" } 
};

var result = dictionary.ReplaceKeyInString(input);
Console.WriteLine(result);

RegEx logic credit goes to @Fabian Bigler. Here is Fabian's answer:

Get values between curly braces c#


Try online


using string interpolation you could do the following

    Dictionary<string, string> dict1 = new() {
    {"entry1", "foo"},
    {"entry2", "bar"}
    };
    string result = $"{dict1["entry1"]} {dict1["entry2"]} this is a string";

You can replace values within {...} with a help of regular expressions:

  using System.Text.RegularExpressions;

  ...

  string str1 = "{entry1} {entry2} this a string";

  Dictionary<string, string> dict1 = new() {
    { "entry1", "foo" },
    { "entry2", "bar" }
  };

  string result = Regex.Replace(str1, @"{([^}]+)}", 
      m => dict1.TryGetValue(m.Groups[1].Value, out var v) ? v : "???");

  // Let's have a look:
  Console.Write(result);

Outcome:

  foo bar this a string