Mariusz
Mariusz

Reputation: 964

Algorithm to display number of views and comments

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

Answers (3)

Aasmund Eldhuset
Aasmund Eldhuset

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

Konstantin Chernov
Konstantin Chernov

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

Thom Smith
Thom Smith

Reputation: 14086

  • Variables prefixed with @ should generally be avoided - they make the code harder to read.
  • The underscore prefix is commonly used for private instance variables. Using it here may be confusing.

For pluralization, check out System.Data.Entity.Design.PluralizationServices.PluralizationService.

http://msdn.microsoft.com/en-us/library/system.data.entity.design.pluralizationservices.pluralizationservice.aspx

Upvotes: 2

Related Questions