Looking for a simple query to truncate text by x amount of characters using Linq.
+2
A:
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));
Justin Niessner
2010-10-05 12:59:51
I decided to make it complicated and convert the word to a char array, use select many, and then use aggregate. Yours is a straight line. I will accept!
FiveTools
2010-10-05 13:20:54
sorry..converted to char array, then i used take and a select, then aggregated the result.
FiveTools
2010-10-05 13:30:17
+1
A:
string raw = raw.ToCharArray().Take(maxLength).Select(x
=> x.ToString()).Aggregate((current,next)
=> current + next);
Which is over complicating...
FiveTools
2010-10-05 13:32:00
You wrote *that* rather than using the `Substring` instance method of `string`? Creative, sure, but... holy bleeding roadkill, batman.
Anthony Pegram
2010-10-05 14:03:09
+1
A:
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
.
Ahmad Mageed
2010-10-05 14:18:18