c# - 如何更新相同项目添加到列表框中的时间?
问题描述
我想在列表框中添加相同的项目时更新现有项目。在当前代码中,相同的值被添加到列表框中。
使用“CollectionChanged + = Eevnt_CollectionChanged”添加新项目时,是否需要检查并删除现有项目并添加新项目?
这是代码:
public class Item: ModelBase
{
private string _nowDate;
public String NOWDATE
{
get { return _nowDate; }
set { _nowDate = value; OnPropertyChanged("NOWDATE"); }
}
private string _name;
public String Name
{
get { return _name; }
set { _name = value; OnPropertyChanged("Name"); }
}
}
private ObservableCollection<Item> _item;
public ObservableCollection<Item> Items
{
get { return _item; }
set
{
_item= value;
OnPropertyChanged("Items");
}
}
... some code ...
while(true){
...
Item.Insert(0, new Item
{
NOWDATE = DateTime.Now.ToString(dateformat),
Name = itemName
}
...
}
请让我知道是否有解决此问题的好方法。
解决方案
您可以使用 Linq 检查该项目是否存在。
不要忘记使用 Linq 库。
using System.Linq;
//Search the list to see if the name exists
//Note, SingleOrDefault throws an error if more than one result is found.
Item updateItem = Items.SingleOrDefault(i => i.Name == itemName);
//Check if the Item exists in the list
if(updateItem != null)
{
//If it does, update the time
updateItem.NOWDATE = newDate;
}
else
{
//If it doesn't, add a new Item
Item.Insert(0, new Item
{
NOWDATE = DateTime.Now.ToString(dateformat),
Name = itemName
}
}
//Now, sort the items so the ones with the earlier date appear first
Items = Items.OrderByDescending(i => i.NEWDATE);
希望这可以帮助。
推荐阅读
- ninja - 忍者能处理长文件名吗?
- r - (自动)在 RStudio 控制台中以各自的颜色显示十六进制字符串?
- python - 如何获取for循环内的文本长度
- php - Zammad API:使用标签创建票证
- amazon-web-services - 如何在 API Gateway (AWS) 的资源策略中使用与 API 密钥关联的标签
- reactjs - 使用 js operator ... 将数据传递到 redux reducer
- amazon-web-services - AWS App-Sync(请求失败,状态码为 403)
- reactjs - “mobx-react”包已弃用?
- r - 如何用颜色而不是r中的线填充折线图中的点?
- flutter - 如何在条件语句中定义 TextStyle