July 29, 2010

StringCollection Class Extender

A helper class for the StringCollection class.
public static class StringCollectionExtender
{
    // Convert a string collection to a multiline string where
    // each entry in the collection becomes a line in 
    // multi-line string
    public static string ToMultilineString(
        this StringCollection sc)
    {
        StringBuilder res = new StringBuilder();
        foreach (string str in sc)
        {
            res.AppendLine(str);
        }
        return res.ToString();
    }

    public static string[] ToStringArray(
        this StringCollection sc)
    {
        string[] res = new string[sc.Count];
        sc.CopyTo(res, 0);
        return res;
    }

    // Convert a multiline string to a string collection with each line
    // of the string becoming a new entry in the collection
    public static StringCollection MultilineStringToStringCollection(
        string str)
    {
        string[] lines = str.Split('\r');
        StringCollection res = new StringCollection();
        foreach (string line in lines)
        {
            res.Add(line.Trim('\n'));
        }
        return res;
    }
}

No comments: