Search code examples
c#sortingstringbuilder

Sort Lines In A StringBuilder


How can one alphabetically sort the lines of a StringBuilder?


Solution

  • If you don't care about the performance, you can do something like this:

        StringBuilder sb = new StringBuilder();
        sb.AppendLine("3333");
        sb.AppendLine("2222");
        sb.AppendLine("1111");
    
        List<string> items = new List<string>(sb.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
        items.Sort();
        sb = new StringBuilder(string.Join("\r\n", items.ToArray()));