1

I have a bit of code, that while simple perhaps isn't immediately obvious as to what it does.

I found @(Model.Count() == 0 ? "no" : Model.Count().ToString()) @(Model.Count() == 1 ? "person" : "people")
@foreach (var item in Model) {
   <div>@item.Name at @item.Email</div>
}

And before I write lots of code like this, I wanted to know if this is a good way of doing this.

Thus the question is, in .NET is there a better framework way of doing this, or is the Ternary method fine

The premise is obviously

  • 0 records = I found no people
  • 1 record = I found 1 person
  • 2+ records = I found 2 people
4

6 回答 6

5

如果您在几个地方这样做,扩展方法将解决您的两个问题(可读性和简化代码)

public static string PersonCountString(this IEnumerable<Person> personList)
{
    var count = personList.Count();
    return String.Format("{0} {1}", count > 0 ? count : "no",
                                    count == 1 ? "person" : "people");
}
...
I found (@Model.PersonCountString())
于 2013-04-24T10:56:37.080 回答
5

在我看来,在Ternary这种情况下使用条件运算符绝对没问题。

有经验的开发者不假思索地理解它,但如果你想让它易于初学者阅读,你也可以使用ifandelse构造。

但我会使用Any()评论中提到的@I4V。

I found @(Model.Any() ? Model.Count().ToString() : "no") @(Model.Count() == 1 ? "person" : "people")


@foreach (var item in Model) {
   <div>@item.Name at @item.Email</div>
}
于 2013-04-24T10:44:20.113 回答
1

回答你的问题:不,我发现 oneliner 不可读,它读起来像@(() 0 ? "" : .().()) @(.() == 1 ? "" : "")我,更不用说多次调用.Count().

您可以像这样创建一个(共享的)辅助方法:

string GetCountWithDescription(int count, 
                               string singleItemDescription, 
                               string multipleItemsDescription)
{
    switch (count)
    {
        case 0:
            return "no " + multipleItemsDescription;
        case 1:
            return "1 " + singleItemDescription;
        default:            
            return count + " " + multipleItemsDescription;
    }
}

也可以重用,所以你可以把它放在一个单独的文件中,这样它就不会弄乱你的代码,你可以简单地从每个视图中调用它,如下所示:

@GetCountWithDescription(Model.Count(), "person", "people")
于 2013-04-24T10:56:20.253 回答
0

你想达到什么目标?更好的可读性或更快的代码(开发)?如果目的是提高可读性,那么我建议将三元运算保留在字符串中,例如:

string modelCountStr = Model.Count() == 0 ? "no" : Model.Count().ToString(); string modelPluralStr = Model.Count() == 1 ? "person" : "people";

于 2013-04-24T10:52:34.937 回答
0

Count()考虑到如果有任何用户存在,您将不得不使用:

@{ 
    var count = Model.Count();
}

I found @(count == 0 ? "no" : count) @(count == 1 ? " person" : " people")
于 2013-04-24T10:53:34.920 回答
0

使其更具可读性的另一种方法是选择一个解决方案,如果可能的话,涉及的条件尽可能少或理想情况为零。

这是我的看法:

@{ 
    var count = Model.Count(); 
}
I found @string.Format(new[] { "no people", "{0} person", "{0} people"} [Math.Min(count, 2)], count)

可以说 Math.Min 负责某种分支,但我认为这更容易理解。

于 2013-04-24T11:54:52.000 回答