Count New Items in WPF Listbox

464 Views Asked by At

I have a listbox and it's source is Binded to a XmlDataProvider. and a RSS link for the source of XmlDataProvider. It's all working correctly, getting feeds and displaying them in the listbox. I have a DispatcherTimer in the code that Refresh the XmlDataProvider source every 10 minutes. Now All I need is to count the new items added in the ListBox in each Refresh Interval.

Can anyone help me to implement a way to count only new items added in the listbox in each Refresh Time Interval? Please Help.

1

There are 1 best solutions below

8
Developer On

I agree with "before adding the item to list count it. – Shujaat Siddiqui", but also you cold add Linq or For cicle, to check if ID of the Item already exists, and count the unique ones. Something like:

int NewItemsCount = 0;
for (int i = 0; i<XmlDataProvider.Items.Count; i++)
{
    bool IsOld=false;
//Loop throu all items in existing
    for (int o =0; i<NewData.Items.Count;i++)
    {
        if(XmlDataProvider.Items[i].ID==NewData.Items[o].ID)
        {
            IsOld = true;
            break;
        }
    }
    if(!IsOld)
    {
         NewItemsCount++;
    }
}

More detailed:

First time when you get the news, you do something like this:

For example you have some model for your news:

class Item
{
    string guid;
    string title;
    ...
}

And you get your news like:

List news = XML.Deserialize(response.GetResponse()) // can't remember by memory, but this is your response from server deserialized using XML deserializer

Then you populate your ListBox with List news, like this:

 ListBox.DataSource = news OR using for/forin and ListBox.Items.Add();

Now you get the update from the server:

List news = XML.Deserialize(response.GetResponse()) // can't remember by memory, but this is your response from server deserialized using XML deserializer

Now you should check how much new items were added ( before adding new items to ListBox ), you should do something like:

a) if you used ListBox.DataSource = news

 List<Item> OldNews = (List<Item>)ListBox.DataSource;
 int newUniqueNewsCount = 0;
 foreach ( Item newObj in news ) // loop through new items that you just got as update from server
 {
      bool IsOld = false;
      foreach ( Item obj in OldNews) // loop through old items
      {
           if(obj.guid==objNew) //check if this GUID already existed
           {
               IsOld = true;
               break; //end the looping
           }
      }
      if(!IsOld)
      {
           // If code ran in here then this GUID is new and then this news is new so +1
           newUniqueNewsCount ++;
      }
 }

After this code ran you can use newUniqueNewsCount to show the new items count in UI.