对象更改后对数组\列表进行排序
当通用列表的对象属性之一发生更改时,对通用列表进行排序的最佳方法是什么?
我有以下示例来帮助解释需要什么。
public class Sending
{
public Sending(int id, DateTime dateSent)
{
this.Id = id;
this.DateSent = dateSent;
}
public int Id { get; set; }
public DateTime DateSent { get; set; }
}
public class Operation
{
public List<Sending> ItemsSent = new List<Sending>();
public Operation()
{
ItemsSent.Add(new Sending(1, new DateTime(2010, 6, 2)));
ItemsSent.Add(new Sending(2, new DateTime(2010, 6, 3)));
ItemsSent[1].DateSent = new DateTime(2010, 6, 1);
}
}
设置 DateSent
属性后,触发列表排序以按日期排序的最佳方法是什么?或者我应该有一种方法来更新属性并执行排序?
What is the best approach for sorting a generic list when one of its objects property is changed?
I have the following example to help explain what is needed.
public class Sending
{
public Sending(int id, DateTime dateSent)
{
this.Id = id;
this.DateSent = dateSent;
}
public int Id { get; set; }
public DateTime DateSent { get; set; }
}
public class Operation
{
public List<Sending> ItemsSent = new List<Sending>();
public Operation()
{
ItemsSent.Add(new Sending(1, new DateTime(2010, 6, 2)));
ItemsSent.Add(new Sending(2, new DateTime(2010, 6, 3)));
ItemsSent[1].DateSent = new DateTime(2010, 6, 1);
}
}
What is the best way to trigger a sort on the list to sort by date after the DateSent
property is set? Or should I have a method to update the property and perform the sort?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在
Sending
上实现IComparable
,并在ItemsSent
上调用Sort()
。我建议编写一种方法来更新对象并手动更新列表。You could implement
IComparable<Sending>
onSending
and callSort()
on theItemsSent
. I would suggest to write a method to update an object and update the list manually.你能做的就是首先实现 INotifyChanged。
然后做一些这样的事情;
因此,每当设置新值时,排序方法都会对列表进行排序。
What you can do is you first implement INotifyChanged.
Then do some thing like this;
So whenever a new value will set the sort method will sort the list.