linq子串?
我收集了一些单词,我想从这个限量为5个字符的集合创建集合
输入:
Car Collection Limited stackoverflow
输出:
car colle limit stack
word.Substring(0,5)抛出exception(长度)
单词.Take(10)也不是好主意
有什么好主意吗?
LINQ到这种情况的对象? 您可以执行以下选择:
from w in words select new { Word = (w.Length > 5) ? w.Substring(0, 5) : w };
从本质上讲,?:解决了这个问题。
var words = new [] { "Car", "Collection", "Limited", "stackoverflow" }; IEnumerable cropped = words.Select(word => word.Substring(0, Math.Min(5, word.Length)));
你可以做的事情是
string partialText = text.Substring(0, Math.Min(text.Length, 5));
我相信你要找的那种答案看起来像这样:
var x = new string[] {"car", "Collection", "Limited", "stackoverflow" }; var output = x.Select(word => String.Join("", word.Take(5).ToList()));
变量“output”包含结果:
car Colle Limit stack
并且字符串“car”不会抛出exception。
但是,尽管Join和Take(5)有效,但它的使用通常要简单得多,正如另一个答案中所建议的那样,
subString = word.Substring(0,Math.Min(5,word.Length));
后一个代码更具人性化和轻量级,但在字符串上使用Linq获取前五个字符肯定有一点冷静因素,而无需检查字符串的长度。