开发者

substring with linq?

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

Input:

Car
C开发者_JAVA百科ollection
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 ??


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.


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

Ranges are available in C# 8, otherwise you'll need to do:

IEnumerable<string> cropped = words.Select(word => 
                                    word.Substring(0, Math.Min(5, word.Length)));


Something you can do, is

string partialText = text.Substring(0, Math.Min(text.Length, 5));


I believe the kind of answer you were looking for would look like this:

var x = new string[] {"car", "Collection", "Limited", "stackoverflow" };
var output = x.Select(word => String.Join("", word.Take(5).ToList()));

The variable "output" contains the result:

car 
Colle 
Limit
stack 

and the string "car" doesn't throw an exception.

But while Join and Take(5) works, it's generally much simpler to use, as was suggested in another answer,

subString = word.Substring(0,Math.Min(5,word.Length));

The latter code is more human-readable and lightweight, though there is definitely a slight coolness factor to using Linq on a string to take the first five characters, without having to check the length of the string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜