Reputation: 964
I have written something like this:
var _views = (@Model.Views == 1 ? "view" : "views");
var _comments = (@Model.Comments == 1 ? "comment" : "comments");
if(@Model.Views > 0)
{
if (@Model.Comments > 0)
{
@String.Format("{0:n0} {1}, {2:n0} {3}", @Model.Views, _views, @Model.Comments, _comments);
}
else
{
@String.Format("{0:n0} {1}", @Model.Views, _views);
}
}
else if (@Model.Comments > 0)
{
@String.Format("{0:n0} {1}", @Model.Comments, _comments);
}
It actually works.
It displays number of views and comments a video has (e.g. http://www.voiceofconscience.org/Video/2 )
There was a singular/plural problem which I have solved in this low quality manner.
I was wondering how it supposed to look like to be considered as a "good style"
Greets Mariusz
Upvotes: 1
Views: 135
Reputation: 37960
This is somewhat more compact, and it generalizes to more than two counts:
var items = new List<string>();
if (Model.Views > 0)
items.Add(string.Format("{0:n0} {1}", Model.Views, _views));
if (Model.Comments > 0)
items.Add(string.Format("{0:n0} {1}", Model.Comments, _comments));
var result = ", ".Join(items);
(Note: all the @
s make it look like you're writing an ASP.NET MVC view, but I can't quite make sense of how you've placed them, so insert @
s where necessary.)
Upvotes: 2
Reputation: 1936
I think it would look better if you'd accumulate result string instead of running into if-else debris. Smth like this:
StringBuilder sb = new StringBuilder();
if(@Model.Views > 0)
sb.AppendFormat("{0:n0} {1}",@Model.Views, _views);
if(@Model.Comments> 0)
sb.AppendFormat("{0:n0} {1}",@Model.Comments, _comments);
Upvotes: 1
Reputation: 14086
For pluralization, check out System.Data.Entity.Design.PluralizationServices.PluralizationService
.
Upvotes: 2