ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

SplitTo

Splits a string into an enumerable collection of the specified type containing the substrings in this instance that are delimited by elements of a specified Char array

Source

/// <summary>
/// Returns an enumerable collection of the specified type containing the substrings in this instance that are delimited by elements of a specified Char array
/// </summary>
/// <param name="str">The string.</param>
/// <param name="separator">
/// An array of Unicode characters that delimit the substrings in this instance, an empty array containing no delimiters, or null.
/// </param>
/// <typeparam name="T">
/// The type of the elemnt to return in the collection, this type must implement IConvertible.
/// </typeparam>
/// <returns>
/// An enumerable collection whose elements contain the substrings in this instance that are delimited by one or more characters in separator. 
/// </returns>
public static IEnumerable<T> SplitTo<T>(this string str, params char[] separator) where T : IConvertible 
{
    foreach (var s in str.Split(separator, StringSplitOptions.None))
        yield return (T)Convert.ChangeType(s, typeof(T));
}

Example

const string str = "1,2,3,4,5,6,7";
var col = str.SplitTo<int>(',');

Author: Magnus Persson

Submitted on: 1 jun 2009

Language: C#

Type: System.String

Views: 5739