对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和CaretPositom,但属性是只读的。

我希望这是清楚的。提前谢谢。

一个不雅但实用的解决方案;richtextbox到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);
}

RichTextBox的工作原理类似于数组,我们可以使用array.sort的方式:

    Dim MyArray() As String
    MyArray = RichTextBox1.Lines
    Array.Sort(MyArray)
    RichTextBox1.Clear()
    For Each item In MyArray
        RichTextBox1.Text &= item & Environment.NewLine
    Next

最新更新