我用下面的:寻找一个简单的方法来截断在C#中的字符串
t.Description.Substring(0, 20)
但有,如果有字符串中少于20个字符的问题。有一种简单的方法(单行内联函数),当字符串少于20个字符时,我可以使用它来截断最大值而不会出现错误?
我用下面的:寻找一个简单的方法来截断在C#中的字符串
t.Description.Substring(0, 20)
但有,如果有字符串中少于20个字符的问题。有一种简单的方法(单行内联函数),当字符串少于20个字符时,我可以使用它来截断最大值而不会出现错误?
如何:
t.Description.Substring(0, Math.Min(0, t.Description.Length));
有点难看,但会起作用。或者,写一个扩展方法:
public static string SafeSubstring(this string text, int maxLength)
{
// TODO: Argument validation
// If we're asked for more than we've got, we can just return the
// original reference
return text.Length > maxLength ? text.Substring(0, maxLength) : text;
}
什么
t.Description.Take(20);
编辑
由于上面的代码将在字符数组infacr结果,正确的代码会是这样:
string.Join("", t.Description.Take(20));
这将返回一个IEnumerable的''
乔恩 - 正如你所看到的,我意识到自己,我不得不说,第一行代码看起来比我编辑之前更好;)。感谢提醒我,有一个字符串构造函数将char数组作为参数。 –
使用
string myShortenedText = ((t == null || t.Description == null) ? null : (t.Description.Length > maxL ? t.Description.Substring(0, maxL) : t));
另:
var result = new string(t.Description.Take(20).ToArray());
我很喜欢这个,因为我已经对字符串使用了一些扩展方法。 –