Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Lines In A StringBuilder

How can one alphabetically sort the lines of a StringBuilder?

like image 312
Steve Macculan Avatar asked Mar 24 '26 05:03

Steve Macculan


1 Answers

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()));
like image 73
HABJAN Avatar answered Mar 26 '26 20:03

HABJAN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!