Skip to content Skip to sidebar Skip to footer

Concatenate A String For Displayfor

I have a model called Lines. On it I have a address class that contains a number of strings, i.e.: public string ReferenceKey { get; set; } public string Country { get; set; } pub

Solution 1:

Add the strings that you want in a list, e.g.:

var str = New List<string>();
if (!string.IsNullOrEmpty(model.Address.ReferenceKey)) {
  str.Add(model.Address.ReferenceKey);
}

Then join the strings:

returnstring.Join(",", str);

Solution 2:

You can do it with a combination of String.Join and a Linq query. The approach below could be made into an extension method on string very easily. You could also use Linq's Aggregate function, but to my mind, String.Join is more intuitive.

This solution will also ensure you don't need to worry about leading or trailing commas.

// Jon all the non-empty address components together.
model.ConcatAddress = string.Join(
    ", ", 
    (newstring[] {
        model.Address.ReferenceKey,
        model.Address.PremisesName,
        model.Address.PostTown,
        model.Address.Postcode,
        model.Address.County,
        model.Address.Country
    }).
    Where(s => !string.IsNullOrEmpty(s)).
    ToArray());

Solution 3:

You need to map the DisplayFor argument to a property in the model, say FullAddress, so you can add a property like:

publicstring FullAddress 
{ 
    get
    {
        string[] addressParts = { ReferenceKey, Country, County, Postcode, PremisesName }
        returnstring.Join(",", addressParts.Where(s => !string.IsNullOrEmpty(s)).ToArray());
    }  
}

And do:

@Html.DisplayFor(model => model.FullAddress)

Solution 4:

You can add a property like this to your model

publicstringFullAddress
{
    get
    {
        returnnewList<string>
            { 
                Address.ReferenceKey,
                Address.PremisesName,
                Address.PostTown,
                Address.PostCode,
                Address.County,
                Address.Country
            }
            .Where(s => !string.IsNullOrWhiteSpace(s))
            .Aggregate((s1, s2) => s1 + "," + s2);
    }
}

I am assuming that by blank fields you mean empty or whitespace, otherwise replace IsNullOrWhiteSpace with IsNullOrEmpty.

Post a Comment for "Concatenate A String For Displayfor"