LINQ to Objects 支持对字符串对象的查询,但是当我使用如下代码时:
string SomeText = "this is some text in a string";
return SomeText.Take(6).ToString();
我得到的只是:
System.Linq.Enumerable+<TakeIterator>d__3a`1[System.Char]
这被称为“意外”这个问题 https://stackoverflow.com/questions/2702390/how-can-i-evaluate-a-deferred-linq-statement-when-debugging但这就是我实际上想做的事情,但我无法通过任何地方的搜索找到它。
我知道还有其他方法来操作字符串,但我也知道您可以使用 LINQ 做一些非常酷的技巧,我只是想知道是否有一种方法可以使用 LINQ 将字符串修剪到一定长度?
System.Linq 中没有内置方法来执行此操作,但您可以相当轻松地编写自己的扩展方法:
public static class StringExtensions
{
public static string ToSystemString(this IEnumerable<char> source)
{
return new string(source.ToArray());
}
}
不幸的是,因为object.ToString
存在于所有 .NET 对象上,您必须为该方法指定不同的名称,以便编译器调用您的扩展方法,而不是内置方法ToString
.
根据您下面的评论,最好质疑这是否是正确的方法。因为String
通过其公共方法公开了很多功能,我会将此方法作为扩展来实现String
itself:
/// <summary>
/// Truncates a string to a maximum length.
/// </summary>
/// <param name="value">The string to truncate.</param>
/// <param name="length">The maximum length of the returned string.</param>
/// <returns>The input string, truncated to <paramref name="length"/> characters.</returns>
public static string Truncate(this string value, int length)
{
if (value == null)
throw new ArgumentNullException("value");
return value.Length <= length ? value : value.Substring(0, length);
}
您可以按如下方式使用它:
string SomeText = "this is some text in a string";
return SomeText.Truncate(6);
这样做的优点是,当字符串已经短于所需长度时,不会创建任何临时数组/对象。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)