2011-10-31 27 views

回答

5

如何:

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; 
} 
+0

我很喜欢这个,因为我已经对字符串使用了一些扩展方法。 –

2

什么

t.Description.Take(20); 

编辑

由于上面的代码将在字符数组infacr结果,正确的代码会是这样:

string.Join("", t.Description.Take(20)); 
+1

这将返回一个IEnumerable的'' - 把它作为你需要'字符串新字符串(t.Description.Take(20).ToArray())'开始相当笨拙 - 而且效率相对较低。 –

+0

乔恩 - 正如你所看到的,我意识到自己,我不得不说,第一行代码看起来比我编辑之前更好;)。感谢提醒我,有一个字符串构造函数将char数组作为参数。 –

0

使用

string myShortenedText = ((t == null || t.Description == null) ? null : (t.Description.Length > maxL ? t.Description.Substring(0, maxL) : t)); 
0

另:

var result = new string(t.Description.Take(20).ToArray()); 
相关问题