有没有更好的方法来编写这个字符串插值?

时间:2017-05-17 08:38:53

标签: c# string-interpolation

我必须编写一段漂亮的代码,但我对以下语法不满意。

有没有更好的方法来编写这个字符串插值?

var details = $"{((currentProfile.FirstName != newProfile.FirstName) ? $"{Environment.NewLine}First Name : {newProfile.FirstName}" : string.Empty)}" +
    $"{((currentProfile.LastName != newProfile.LastName) ? $"{Environment.NewLine}Last Name : {newProfile.LastName}" : string.Empty)}" +
    $"{((currentProfile.MiddleName != newProfile.MiddleName) ? $"{Environment.NewLine}Middle Name : {newProfile.MiddleName}" : string.Empty)}" +
    $"{((currentProfile.Suffix != newProfile.Suffix) ? $"{Environment.NewLine}Suffix : {newProfile.Suffix}" : string.Empty)}" +
    $"{((currentProfile.AddressLine1 != newProfile.AddressLine1) ? $"{Environment.NewLine}Address Line 1 : {newProfile.AddressLine1}" : string.Empty)}" +
    $"{((currentProfile.AddressLine2 != newProfile.AddressLine2) ? $"{Environment.NewLine}Address Line 2 : {newProfile.AddressLine2}" : string.Empty)}" +
    $"{((currentProfile.City != newProfile.City) ? $"{Environment.NewLine}City : {newProfile.City}" : string.Empty)}"+
    $"{((currentProfile.ProvinceCode != newProfile.ProvinceCode) ? $"{Environment.NewLine}State : {newProfile.ProvinceCode}" : string.Empty)}" +
    $"{((currentProfile.ZipCode != newProfile.ZipCode) ? $"{Environment.NewLine}Zip Code : {newProfile.ZipCode}" : string.Empty)}" + 
    $"{((currentProfile.CountryCode != newProfile.CountryCode) ? $"{Environment.NewLine}Country : {newProfile.CountryCode}" : string.Empty)}" +
    $"{((currentProfile.Phone != newProfile.Phone) ? $"{Environment.NewLine}Phone : {newProfile.Phone}" : string.Empty)}";

2 个答案:

答案 0 :(得分:5)

个人我可能会使用类似的东西:

var sb = new StringBuilder();
AppendIfDifferent(sb, currentProfile.FirstName, newProfile.FirstName, "First Name");
AppendIfDifferent(sb, currentProfile.LastName, newProfile.LastName, "Last Name");
// ...
string s = sb.ToString();

使用:

static void AppendIfDifferent(StringBuilder sb, string newValue,
        string oldValue, string label)
{
    if(newValue != oldValue)
    {
        sb.AppendLine().Append(label).Append(" : ").Append(newValue);
    }
}

答案 1 :(得分:1)

您可以通过制作扩展方法来简化:

public static class ExtensionMethods
{
    public static string IfNotEquals(this string s1, s2, string label)
    {
        if (s1 != s2)
        {
            return label + s1;
        }

        return null;
    }
}

您可以这样使用:

$"{currentProfile.LastName.IfNotEquals(newProfile.LastName, "Last name:")}"