【问题标题】:How to add a placeholder curly braces in dictionary keys如何在字典键中添加占位符花括号
【发布时间】:2018-09-25 14:39:56
【问题描述】:

所以,我有一本像下面这样的字典:

Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("first", "Value1");
dict.Add("second", "Value2");

我有一个如下字符串:

rawMsg = "My values are {first} and {second}.";

预期输出:

My values are Value1 and Value2.

字符串格式化代码:

public void Format(string rawMsg, Dictionary<string, object> dict)
{
    var temp = dict.Aggregate(rawMsg, (current, parameter) => current.Replace(parameter.Key, parameter.Value.ToString())); 
}

为了使上述代码正常工作,我需要添加如下键:

Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("{first}", "Value1"); // Notice the curly braces in Keys
dict.Add("{second}", "Value2");

但我不想在键中添加花括号。

我想在我的 format 逻辑中附加花括号。

伪代码:

public void Format(string rawMsg, Dictionary<string, object> dict)
{
    // loop through all the keys and append a curly braces in them.
    var temp = dict.Aggregate(rawMsg, (current, parameter) => current.Replace(parameter.Key, parameter.Value.ToString())); 
}

但我不知道一种有效的方法。请指导我。

【问题讨论】:

    标签: c# .net dictionary


    【解决方案1】:

    在需要时添加即可?

    public void Format(string rawMsg, Dictionary<string, object> dict)
    {
        var temp = dict.Aggregate(rawMsg, (current, parameter) => current.Replace("{" + parameter.Key + "}", parameter.Value.ToString())); 
    }
    

    【讨论】:

    • @Unbreakable 请注意,如果您正在寻找一种“高效”的方法来执行此操作,则此解决方案(在工作时)可能不是最佳选择,因为对于每个键,它会执行 2 个字符串连接和扫描整个字符串以查找候选替换。基于正则表达式的解决方案(如 Dmitry Bychenko 的解决方案)会表现得更好,尤其是在字典中有很多项目的情况下。
    【解决方案2】:

    如果您要创建自己的字符串插值,我建议正则表达式,例如:

      Dictionary<string, object> dict = new Dictionary<string, object>() {
        {"first", "Value1" },
        {"second", "Value2" },
      };
    
      string rawMsg = "My values are {first} and {second}.";
    
      string result = Regex.Replace(
        rawMsg, 
       @"\{[^{}]+?\}", 
        match => dict[match.Value.Substring(1, match.Value.Length - 2)]?.ToString());
    
      Console.Write(result);
    

    结果:

      My values are Value1 and Value2.
    

    P.S.我假设您希望一次性完成所有更改,即为

      Dictionary<string, object> dict = new Dictionary<string, object>() {
        {"first", "{second}" },
        {"second", "third" },
      };
    
      string rawMsg = "My values are {{first}} and {second}.";
    

    正确答案是

      My values are {second} and third.
    

    不是(我们不想处理second两次

      My values are third and third.
    

    【讨论】:

    • 我相信 OP 希望结果没有花括号字符。否则,很好的答案。
    • @vinicius.ras:谢谢!我已经编辑了我的答案和问题(突出显示了所需的结果)
    • 我认为这个解决方案比公认的解决方案更有效,后者涉及多个字符串连接并调用string.Replace
    【解决方案3】:

    这应该可行。简而言之,创建一个正则表达式并将其存储在静态成员中以仅编译一次,然后使用它用字符串中的值替换占位符出现 (Fiddle)。

    private static Regex _regex = new Regex(@"(?<={)(\w+)");
    
    ...
    
    public string Format(string rawMsg, IReadOnlyDictionary<string, object> dict) =>
    
        _regex.Replace(rawMsg, match =>
        {
            string placeHolder = match.ToString();
    
            return dict.TryGetValue(placeHolder, out object placeHolderValue) 
                       ? placeHolderValue.ToString() : null;
        });
    

    请注意,第一个正则表达式组是非捕获的,以便从捕获中排除花括号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-13
      • 2013-10-01
      • 2021-04-18
      • 1970-01-01
      • 2017-01-15
      • 1970-01-01
      • 2019-07-03
      • 2018-11-17
      相关资源
      最近更新 更多