具有布尔值的String.Replace()?

时间:2018-07-19 05:30:38

标签: c#

我有Dictionary<string,dynamic>个键值对。

我还有一个字符串script,在其中我需要用字典中的相应值替换所有出现的键。

例如:词典的内容:

Param1 : true
Param2 : "False"
Param3 : 123
Param4 : "1234"

String script = " I have Param1 and Param2 and Param3 and Param4 "

现在我希望将其转换为

script = " I have true and "False" and 123 and "1234" "

我该如何实现?我已经尝试过script.Replace(),但是它不适用于string以外的数据类型,如果我将ToString()用于其他数据类型,则会将Boolean的值变为大写。

编辑:我也通过此链接Why does Boolean.ToString output "True" and not "true"

3 个答案:

答案 0 :(得分:0)

尝试一下:

var map = new Dictionary<string, object>()
{
    { "Param1", true },
    { "Param2", "False" },
    { "Param3", 123 },
    { "Param4", "1234" },
};

var script = " I have Param1 and Param2 and Param3 and Param4 ";

var output = map.Aggregate(script,
    (s, kvp) => s.Replace(kvp.Key, kvp.Value is string ? $"\"{kvp.Value}\"" : kvp.Value.ToString()));

相当于:

var output = " I have True and \"False\" and 123 and \"1234\" ";

您可能只需要一个。ToLower()

答案 1 :(得分:0)

通过RegularExpressions使用模式"Param\\d+",您可以将String.Relace()用于找到的匹配项。您将需要检查地图中的值是否为bool类型,以便可以String.ToLower()获得所需的结果。

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

public class Program
{
    public static void Main()
    {
        var map = new Dictionary<string, object>()
        {
            { "Param1", true },
            { "Param2", "\"False\"" },
            { "Param3", 123 },
            { "Param4", "\"1234\"" },
        };

        var script = " I have Param1 and Param2 and Param3 and Param4 ";
        MatchCollection matches = Regex.Matches(script, "Param\\d+");
        foreach (Match match in matches)
        {
            object val = map[match.Value];
            script = script.Replace(match.Value, val is bool ? val.ToString().ToLower() : val.ToString());
        }

        Console.WriteLine(script);
    }
}

结果:

 I have true and "False" and 123 and "1234"

Fiddle Demo

答案 2 :(得分:0)

您可以按照以下方式进行操作。

Boolean x = false;
Dictionary<string, dynamic> k = new Dictionary<string, dynamic>();
k.Add("Param1", x.ToString().ToLower());
k.Add("Param2", 123);
Console.WriteLine(string.Format("hi {0} -- {1}", k.Values.ToArray()));