首页 > 解决方案 > 如何更新相同项目添加到列表框中的时间?

问题描述

我想在列表框中添加相同的项目时更新现有项目。在当前代码中,相同的值被添加到列表框中。

使用“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 所示。 在此处输入图像描述

请让我知道是否有解决此问题的好方法。

标签: c#wpflistboxobservablecollection

解决方案


您可以使用 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);

希望这可以帮助。


推荐阅读