2011-10-31 32 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()); 
相關問題