在我的项目中,我有这个课:
public class AccountData
{
private const string DATE_FORMAT = "dd/MM/yyyy HH:mm";
private string userName;
private long creationDate, lastModificationDate;
public ProjectData()
{
this.userName = Environment.UserName;
creationDate = lastModificationDate = DateTime.Now.Ticks;
}
public void UpdateLastModified()
{
lastModificationDate = DateTime.Now.Ticks;
}
#region Properties
public string CreationDate => new DateTime(creationDate).ToString(DATE_FORMAT);
public string LastModificationDate => new DateTime(lastModificationDate).ToString(DATE_FORMAT);
public string UserName => userName;
#endregion
}
And I need to display a list of this class (System.Generic.List<AccountData>()
).
我能够正确显示它,但我还想添加一个选项,以按参数之一对数据进行排序。即,如果用户选择了按creationDate排序,则列表中的所有项目都会被该值破坏。
但是我找不到灵活的解决方案。
到目前为止,这是我得到的:
private void SortItemsBy(string by)
{
List<AccountData> accounts = GetAccounts();
switch (by)
{
case "Last Modified":
Sort(accounts, data => data.LastModificationDate);
break;
case "Creation Date":
Sort(accounts, data => data.CreationDate);
break;
case "User Name":
Sort(accounts, data => data.UserName);
break;
}
}
private void Sort(IEnumerable<AccountData> accounts, Func<AccountData, string> predicate)
{
var orderedAccounts = accounts.OrderBy(predicate);
DisplayAccounts(orderedAccounts);
}
如您所见,我将排序基于一个字符串值(据我所知),该值很容易出错。
有更好的方法吗?