This question has probably already been answered somewhere but I’m having a hard time formulating it correctly which makes it hard finding anything about it.
Let’s say I have items in my WinForms application which have an expiration date. I have more different conditions than this one but let’s do it simple. I’d like to trigger an event when an item comes to expiration. What is the ideal way to do so? Checking every X minutes? I’m confused as if this is the best solution.
code samples in both VB.net or C# are welcome.
Thank you
Use either the SortedDictionary like CodeInChaos mentioned, or a SortedList. Choose which one based on the “Remarks” section for each. Both have O(log n) retrieval since they’re implemented as a binary search tree (that I assume is somehow balanced). Both will be marginally faster in specific circumstances described in their documentation.
Basically the idea is to maintain two data structures:
Your collection of items
A sorted collection of references to the items sorted by their expiration date.
You need some sort of Update() loop that will just look at the first index of the Values property of your SortedList or SortedDictionary (O(1) operation) and see if the system date is past that item’s expiration date.
Here’s simple usage with just strings and ints:
Whenever you add a new item to your main collection, add a reference to it in this SortedList/SortedDictionary and provide the expiration date as the key to sort by. Storing the references requires a little more memory overhead, but like CodeInChaos said, it will be much faster. I don’t think it’s terribly difficult to code though.