首页 > 解决方案 > 反转显示字符串的顺序

问题描述

我目前是一个c# winforms正在做一个小项目的初学者。我不太明白如何切换笔记的顺序。

目前我有一个笔记课和一个Addnote按钮。该按钮的作用是从一个文本框中获取我的输入,并将其显示在另一个文本框中。

目前我已经尝试过.Reverse()

private void btnAddNote_Click(object sender, EventArgs e)
{                 
    Notes note = new Notes(txtNoteWriter.Text);           
    txtNoteReader.Text += note.Note + Environment.NewLine + DateTime.Now + Environment.NewLine + Environment.NewLine;
    txtNoteReader.Text.Reverse();
}

我的课看起来像这样

class Notes
{
    public string Note { get; set; }

    public Notes(string note)
    {
        Note = note;           
    }

    public override string ToString()
    {
        return Note;
    }       
}

我将注释添加txtNoteWriter到只读的按钮txtNoteReader

private void btnAddNote_Click(object sender, EventArgs e)
{                 
    Notes note = new Notes(txtNoteWriter.Text);           
    txtNoteReader.Text += note.Note + Environment.NewLine + DateTime.Now + Environment.NewLine + Environment.NewLine;
}

目前,我正试图让它根据提交时间保存最新到最旧的注释(目前它的顺序相反。)。

标签: c#winforms

解决方案


有几种方法可以实现这一点,以下是一个建议。

由于您需要时间戳以及添加的字符串,因此您可以将其作为 Notes 类的一部分。例如,修改notes类如下。

class Notes
{
    public string Note { get; set; }

    public DateTime TimeStamp { get; set; }

    public Notes(string note)
    {
        Note = note;
        TimeStamp = DateTime.Now;
    }
    public override string ToString()
    {
        return $"{Note}-{TimeStamp.ToString()}";

    }
}

现在,您可以在 Main 类中定义一个集合来保存每个添加的 Note。

private List<Notes> _notesCollection = new List<Notes>();

最后,btnAddNote 点击事件如下所示

private List<Notes> _notesCollection = new List<Notes>();
private void btnAddNote_Click(object sender, EventArgs e)
{
    var note = new Notes(txtNoteWriter.Text);
    _notesCollection.Add(note);
    txtNoteReader.Text = string.Join(Environment.NewLine, _notesCollection.OrderByDescending(x => x.TimeStamp).Select(x => x.ToString()));
}

在按钮 Click 事件中,您正在向集合中添加一个新注释。然后,您使用 LINQ 根据 TimeStamp 属性对集合进行排序。为此,您正在使用OrderByDescending方法。Select方法使您能够从集合中选择需要显示的内容。

最后,string.Join方法允许您连接不同的字符串以形成最终结果。


推荐阅读