I need a function like this:
AddToList(txtName, timeExpire);
It looks like self-descriptive, the item will automatically expire and removed
You will need to create an object that can manage this.
Think about what it will need to store per item. Basically, the data (e.g. txtName
), and an expiry time. That means you probably will need a class or struct that just has those 2 elements.
Your ExpiringList
class will be a list of that type.
Now you have your basic data structure (a collection/list of ExpiringListItem
) you need to think about what operations you want to support. Currently you've listed AddToList, others would probably be RemoveFromList, Clear, and maybe iterating over all items.
The only thing unique to your ExpiringList compared to a normal List
is that you want to automatically remove expired items. Therefore it would make sense to make your ExpiringList implement the interface IList
and use a private List internally, possibly you could make your list (and by necessity your ExpiredListItem
class) generic.
The tricky part, beyond understanding and implementing inheritance (a separate question really), is working out how to remove expired items.
This would mean creating a method within your class that iterated (in reverse order) over your items, comparing their expiry time with the current time and removing expired ones.
You could implement the interface simply by calling the appropriate methods on your internal list.
You could say at this point, you're done, since you just call that method periodically to ensure sure all expired items are gone before you use the items in the list.
Maybe a better option would be to call this method before running the method on the internal list. Depending on how you will use your list this may be overkill.