Tiny way to get the first 25 characters

后端 未结 12 1570
感动是毒
感动是毒 2020-12-29 13:12

Can anyone think of a nicer way to do the following:

public string ShortDescription
{
    get { return this.Description.Length <= 25 ? this.Description :          


        
12条回答
  •  借酒劲吻你
    2020-12-29 13:59

    One way to do it:

    int length = Math.Min(Description.Length, 25);
    return Description.Substring(0, length) + "...";
    

    There are two lines instead of one, but shorter ones :).

    Edit: As pointed out in the comments, this gets you the ... all the time, so the answer was wrong. Correcting it means we go back to the original solution.

    At this point, I think using string extensions is the only option to shorten the code. And that makes sense only when that code is repeated in at least a few places...

提交回复
热议问题