简体   繁体   中英

truncate text using linq

寻找一个简单的查询以使用Linq通过x个字符截断文本。

Your question is unclear. Based on your comment to Justin's answer it sounds like the simpler way to achieve what you're describing would be as follows:

string input = "The quick brown fox jumped over the lazy dog";
string result = new String(input.Take(15).ToArray());
Console.WriteLine(result);

Notice that there is no need to call ToCharArray() since a string implements IEnumerable<char> . IntelliSense in VS2008 does not show up but the extension methods still work. Likewise, you can use the string constructor and pass it an array of characters instead of using Aggregate .

You could use a pretty simple combination of Select and Substring to truncate the strings to a certain length:

var words = new List<string>();

// fill the list of words

var truncated = words.Select(w => w.Substring(0, 15));
string raw = raw.ToCharArray().Take(maxLength).Select(x
=> x.ToString()).Aggregate((current,next)
=> current + next);

Which is over complicating...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM