什么是在RichTextBox中对行进行排序的最佳方法

我正在寻找排序RichTextBox行的最佳方法,我现在正在使用它:

public void SortLines(object sender, EventArgs e) { TextPointer pStart = TextInput.Document.ContentStart; TextPointer pEnd = TextInput.Document.ContentEnd; TextRange text = new TextRange(pStart, pEnd); string[] lines = text.Text.Split('\n'); Array.Sort(lines); text.Text = String.Join(String.Empty, lines); } 
  1. 有最好的方法吗?

  2. 当我调用它时,光标被放入第一个RichTextBox行,我该如何将它放在之前的位置? 我尝试设置pStart / pEnd和CaretPositiom,但属性是只读的。

我希望这很清楚。 提前致谢。

一个不优雅但实用的解决方案; 来回富文本框到ListBox:在listBox的属性中,单击“已排序”>“真”

[C#]

 ListBox1.Items.AddRange(RichTextBox1.Lines); for (int x = 0; (x <= (ListBox1.Items.Count - 1)); x++) { RichTextBox1.AppendText((ListBox1.Items(x).ToString.Environment.NewLine)); } 

[VB.NET]

 ListBox1.Items.AddRange(RichTextBox1.Lines) For x As Integer = 0 To ListBox1.Items.Count - 1 RichTextBox1.AppendText(ListBox1.Items(x).ToString & Environment.NewLine) Next 

至于排序这个解决方案与你建议的不同,但我发现它更优雅+它处理光标位置和选择:

 public void SortLines(object sender, EventArgs e) { rtb.HideSelection = false; //for showing selection /*Saving current selection*/ string selectedText = rtb.SelectedText; /*Saving curr line*/ int firstCharInLineIndex = rtb.GetFirstCharIndexOfCurrentLine(); int currLineIndex = rtb.Text.Substring(0, firstCharInLineIndex).Count(c => c == '\n'); string currLine = rtb.Lines[currLineIndex]; int offset = rtb.SelectionStart -firstCharInLineIndex; /*Sorting*/ string[] lines = rtb.Lines; Array.Sort(lines, delegate(string str1, string str2) { return str1.CompareTo(str2); }); rtb.Lines = lines; if (!String.IsNullOrEmpty((selectedText))) { /*restoring selection*/ int newIndex = rtb.Text.IndexOf(selectedText); rtb.Select(newIndex, selectedText.Length); } else { /*Restoring the cursor*/ //location of the current line int lineIdx = Array.IndexOf(rtb.Lines, currLine); int textIndex = rtb.Text.IndexOf(currLine); int fullIndex = textIndex + offset; rtb.SelectionStart = fullIndex; rtb.SelectionLength = 0; } } 

感谢Eric Paroissien提供的简单解决方案! C#代码有几个问题 – 这是他的修复解决方案

 ListBox1.Items.Clear(); ListBox1.Items.AddRange(RichTextBox1.Lines); RichTextBox1.Clear(); for (int x = 0; (x <= (ListBox1.Items.Count - 1)); x++) { RichTextBox1.AppendText(ListBox1.Items[x].ToString()); RichTextBox1.AppendText(Environment.NewLine); }