当相同的项目被添加到列表框时,如何更新时间?
How can I update the time when the same item is added to the list box?
我想在列表框中添加相同项目时更新现有项目。在当前代码中,相同的值被添加到列表框中。
使用"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
}
...
}
图 1 显示了当前列表框的结果。
我只想显示最近的一个,如图2所示。
请告诉我是否有解决此问题的好方法。
您可以使用 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);
希望对您有所帮助。
我想在列表框中添加相同项目时更新现有项目。在当前代码中,相同的值被添加到列表框中。
使用"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
}
...
}
图 1 显示了当前列表框的结果。
我只想显示最近的一个,如图2所示。
请告诉我是否有解决此问题的好方法。
您可以使用 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);
希望对您有所帮助。