Chris Cannon
Chris Cannon

Reputation: 1167

.NET object remove itself from collection / enumeration

This is probably impossible / bad idea but...

Is it possible for an object to remove itself from a collection / enumeration, or for the object to be "skipped" when it is data bound?

So the object effectively says "skip me when data binding".

Upvotes: 1

Views: 76

Answers (1)

Morten Mertner
Morten Mertner

Reputation: 9474

That is technically two completely separate questions.

Q1 - can an object remove itself from a collection? This depends largely on the collection class being used. One obvious requirement is that the contained object must hold a reference to the collection within which it is contained. Another requirement is that it cannot happen while the collection is being enumerated. This is probably not a path you want to walk along.

Q2 - can an object be skipped when data binding? I'm not aware of any built-in collection class that supports this, but it should be possible by writing a custom enumerator (that examines the elements and skips those that should be excluded) for the container class.

That said, it is probably easier to use a LINQ query as the data source:

List<Foo> foos = new List<Foo>();
var query = foos.Where( f => f.IsNotExcluded );
BindingSource bs = new BindingSource( query ); // bind to query instead of foos

You can also expose the filtered list as a property, in case you need that:

public class FooManager
{
    private List<Foo> foos = new List<Foo>();

    public IQueryable<Foo> OnlyEnabledFoos
    {
        return foos.Where( f => f.IsNotExcluded ).AsQueryable();
    }
}

Hope this helps!

Upvotes: 1

Related Questions