字符串长度并与 int 比较

string length and compare to int

为什么这不起作用? 如果 teaserLength 例如 returns 300,则为真。 如果它 returns 例如 37,它是错误的。即使它应该被颠倒......

我的代码:

@{
     int teaserLength = item.TeaserText.Length;
}
@if (teaserLength >= 75)
{
     @item.TeaserText
}
else { 
     @item.TeaserText.Substring(1, 75)
}

以及为什么长度为 37 的 TeaserText 给出

ArgumentOutOfRangeException
Index and length must refer to a location within the string.

在子串上 ?

Substring 中的 "starting" 索引是从零开始的,如果长度为 75 或更多,您只需要子字符串:

@if (teaserLength >= 75)
{
     @item.TeaserText.Substring(0, 75)
}
else { 
     @item.TeaserText
}

或者只是

@item.TeaserText.Substring(0, Math.Min(teaserLength, 75))

再次阅读您自己的 if 陈述。

@if (teaserLength >= 75)
{
     @item.TeaserText
}
else { 
     @item.TeaserText.Substring(1, 75)
}

"If teaserLength is greater than or equal to 75, use the text, else take the substring."

不能取长度小于75的字符串的长度为75的子串

要解决此错误,只需将 >= 运算符换成 < 运算符即可。

此外,您可能希望将 .Substring(1, 75) 换成 .Substring(0, 75),假设您希望将字符串截断为 75 个字符。 正如@RufusL 正确提到的那样,否则长度为 75 的字符串会出现异常。

另一种方法是使用 Min 函数:

@{
    int maxCharsToDisplay = Math.Min(item.TeaserText.Length, 75);
}

@item.TeaserText.Substring(0, maxCharsToDisplay);

对于值小于 75 的情况,Min 将 return 该长度;如果值较大,75 将被 returned。您最多只能有 75 个字符。

另一种方法是使用 System.Linq 并仅 Take 您想要的最大项目数 (75),然后 Concat 它们:

string.Concat(item.TeaserText.Take(75));