Problem with Substring() - ArgumentOutOfRangeException

后端 未结 11 1723
抹茶落季
抹茶落季 2020-12-20 11:29

I have a repeater that displays data from my Projects table. There are projectId, name and description. I use Substring(1, 240) on description. But sometimes the string is s

11条回答
  •  借酒劲吻你
    2020-12-20 12:22

    Let's try to keep this simple...

    We only need to truncate to a given max length, so how about we call it what it is:

    description.TruncateTo(240);
    

    The extension method that enables the above (ellipsis is appended by default if truncated):

    public static class StringExtensions
    {
        public static string TruncateTo(this string val, int maxLength, bool ellipsis = true)
        {
            if (val == null || val.Length <= maxLength)
            {
                return val;
            }
    
            ellipsis = ellipsis && maxLength >= 3;
            return ellipsis ? val.Substring(0, maxLength - 3) + "..." : val.Substring(0, maxLength);
        }
    }
    

提交回复
热议问题