これを行うために 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
自体の拡張機能として実装します。
/// <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);
これには、文字列が目的の長さよりもすでに短い場合に、一時的な配列/オブジェクトを作成しないという利点があります。