문제

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?

도움이 되었습니까?

해결책

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
    }
}

다른 팁

Try:

items.Where(e => e.isVisible == true).ToList()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top