الثلاثاء، 24 ديسمبر 2013

How can I extend Collection to provide a filtered object collection?

I'm trying to create a collection that acts just like all other collections, except when you read out of it, it can be filtered by setting a flag.

Consider this (admittedly contrived) example:

var list = new FilteredStringList() { "Annie", "Amy", "Angela", "Mary"};list.Filter = true;

I added four items, but then I set the "Filter" flag, so that whenever I read anything out of it (or do anything that involves reading out of it), I want to filter the list to items that begin with "A".

Here's my class:

public class FilteredStringList : Collection{ public bool Filter { get; set; } protected new IList Items { get { if(Filter) { return base.Items.Where(i => i.StartsWith("A")).ToList(); } return base.Items; } } public IEnumerator GetEnumerator() { foreach(var item in Items) { yield return item; } }}

My theory is that I'm overriding and filtering the Items property from the base Collection object. I assumed that all other methods would read from this collection.

If I iterate via ForEach, I get:

AnnieAmyAngela

Yay! But, if I do this:

list.Count()

I get "4". So, Count() is not respecting my filter.

And if I do this:

list.Where(i => i[1] == 'a')

I still get "Mary" back, even though she shouldn't be there.

I know I can override all sorts of the Collection methods, but I don't really want to override them all. Additionally, I want all the LINQ methods to respect my filter.


View the original article here

ليست هناك تعليقات:

إرسال تعليق