tags:

views:

219

answers:

2

I've got collection of words, and i wanna create collection from this collection limited to 5 chars

Input:

Car
Collection
Limited
stackoverflow

Output:

car
colle
limit
stack

word.Substring(0,5) throws exception (length)

word.Take(10) is not good idea, too...

Any good ideas ??

+11  A: 

Hey,

LINQ to objects for this scenario? You can do a select as in this:

from w in words
select new
{
  Word = (w.Length > 5) ? w.Substring(0, 5) : w
};

Essentially, ?: gets you around this issue.

Brian
You should add a check for `null` elements. That is, `var subwords = words.Where(w => w != null).Select(w => w.Length > 5 ? w.Substring(0, 5) : w);`.
Jason
+3  A: 

var words = new [] { "Car", "Collection", "Limited", "stackoverflow" }; IEnumerable<string> cropped = words.Select(word => word.Substring(0, Math.Min(5, word.Length));

Paul Ruane