Question

This code doesn't work, but:

public virtual ICollection<SomeItem> items { get { return (ICollection<SomeItem>)items.Where(e => e.isVisible == true); } set { ;} }

I'd like to do something to that effect. So to get an ICollection filtered by a property of the collection's elements.

Sure, I could iterate through the elements, and get the right ones, put them in a new collection and return with that, but is there a nicer solution?

Was it helpful?

Solution

Perhaps what you're looking for is an Extension Method?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

public static class ExtensionMethods
{
    public static ICollection<SomeItem> OnlyVisible(this ICollection<SomeItem) items) {
        return items.Where(e => e.isVisible).ToList();
    }
}

Note that Where returns an IEnumerable, which you cannot modify, so I call ToList() which essentially does everything in your last sentence.

You would then use it like this:

void Foo(ICollection<SomeItem> items) {

    foreach (var i in items.OnlyVisible()) {
        // Use i
    }
}

OTHER TIPS

Try:

items.Where(e => e.isVisible == true).ToList()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top