3

我有一个带有消息的字符串,其中包含一些我想换成实际值的字段

var message = "Hi [CustomerName]. Its [TODAY], nice to see you were born on the [DOB]!";
var mappingCodes = new List<string> {"[CUSTOMER_NAME]","[DOB]",[TODAY]};
var customEmails = new Dictionary<string, string>();
var today = DateTime.Now;
var customers = new List<Customer>()
{
    new Customer()
        {
            FirstName = "Jo",
            LastName = "Bloggs",
            Email = "jo@bloggs.com",
            DOB = "10/12/1960"
        }
};
foreach (var customer in customers)
{
    var emailMessage = "";
    customEmails.Add(customer.Email,emailMessage);
}

我正在尝试做的是遍历每个客户并将消息替换为实际代码中的任何映射代码。
例如 [Today] 将是今天并且CustomerName将是Customer.FirstName + Customer.LastName

可能有 1000 名客户,所以我需要一些强大的东西。我只是不确定如何首先检查字符串是否包含任何一个mappingCodes,然后用所需的值替换它们。

有什么建议吗?

4

2 回答 2

2

你可以试试这样的。String.Format 相当有效。如果需要,它还允许您格式化 Date.Today。

var customers = new List<Customer>()
{
    new Customer()
    {
        FirstName = "Jo",
        LastName = "Bloggs",
        Email = "jo@bloggs.com",
        DOB = "10/12/1960"
    }
};
foreach (var customer in customers)
{
    var emailMessage = String.Format("Hi {0}. Its {1}, nice to see you were born on the {2}!", customer.FirstName, DateTime.Today, customer.DOB);
    customEmails.Add(customer.Email,emailMessage);
}
于 2012-11-03T00:37:46.173 回答
1

您可以使用Regex.Replace(string, MatchEvaluator)

var customers = new[] {
    new {
        Name = "Fred Flintstone",
        City = "Bedrock"
    },
    new {
        Name = "George Jetson",
        City = "Orbit City"
    }
};

string template = "Hello, [NAME] from [CITY]!";
var re = new Regex(@"\[\w+\]"); // look for all "words" in square brackets

foreach (var customer in customers)
{
    Trace.WriteLine(
        re.Replace(template, m => {
            // determine the replacement string
            switch (m.Value) // m.Value is the substring that matches the RE.
            {
                // Handle getting and formatting the properties here
                case "[NAME]":
                    return customer.Name;
                case "[CITY]":
                    return customer.City;
                default:
                    // The "mapping code" is not supported, I just return the 
                    // original substring
                    return m.Value;
            }
        }));
}

显然以上只是一般方法,您必须对其进行修改以支持您的映射代码和数据结构。

于 2012-11-03T00:36:42.857 回答