c# - 反转显示字符串的顺序
问题描述
我目前是一个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;
}
目前,我正试图让它根据提交时间保存最新到最旧的注释(目前它的顺序相反。)。
解决方案
有几种方法可以实现这一点,以下是一个建议。
由于您需要时间戳以及添加的字符串,因此您可以将其作为 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方法允许您连接不同的字符串以形成最终结果。
推荐阅读
- docker - 在构建 docker 映像期间无法访问卷
- java - 第一个字母和最后一个字母,第二个字母和倒数第二个字母的差之和,依此类推,直到单词的中心
- javascript - 两个输入相同时启用按钮
- php - 如何使用按钮停止会话?
- c# - IIS System.IO.DirectoryNotFoundException
- avahi - avahi 编译错误“找不到 libgdbm.so”ubuntu 16.04?
- sql-server - 是否可以将 NULL 从 Typescript 传递到 SQL Server 存储过程
- c# - 此平台不支持文件加密
- azure - Azure:将 ASP.Net Core SDK 更新到 1.0 到 2.1.203 并收到有关 System.Data.SqlClient 的错误
- regex - Angular2-6、正则表达式和输入装饰器