lost_in_the_source
lost_in_the_source

Reputation: 11237

How do I check if the count of a list is increasing?

I have this list:

List<string> x=new List<string>

So, now I want to do something when the count is being increased. I tried:

if(x.Count++){
  //do stuff
}

But it did not work. So what can I try?

Upvotes: 0

Views: 168

Answers (1)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137467

You can't do this like you're trying to do. if (x.Count++) makes no sense - you're attempting to increment the count (which is read-only).

I would derive from List<T> and add ItemAdded and ItemRemoved events.

Actually, that would be re-inventing the wheel. Such a collection already exists. See ObservableCollection<T>, which raises a CollectionChanged event. The NotifyCollectionChangedEventArgs tells you what changed.

Example (not tested):

void ChangeHandler(object sender, NotifyCollectionChangedEventArgs e ) {
    switch (e.Action) {
        case NotifyCollectionChangedAction.Add:
            // One or more items were added to the collection.
            break;
        case NotifyCollectionChangedAction.Move:
            // One or more items were moved within the collection.
            break;
        case NotifyCollectionChangedAction.Remove:
            // One or more items were removed from the collection.
            break;
        case NotifyCollectionChangedAction.Replace:
            // One or more items were replaced in the collection.
            break;
        case NotifyCollectionChangedAction.Reset:
            // The content of the collection changed dramatically.
            break;
    }

    // The other properties of e tell you where in the list
    // the change took place, and what was affected.
}

void test() {
    var myList = ObservableCollection<int>();
    myList.CollectionChanged += ChangeHandler;

    myList.Add(4);
}

References:

Upvotes: 5

Related Questions