Given the following class:
public class GenClass<T>
{
private List<T> ItemsList {get;set;}
public Predicate<T> SomeCondition {get;set;}
public bool UsePredicate {get;set;}
public List<T> Items
{
get { //CODE Goes here; }
}
}
I need a way for the list to use the SomeConditionPredicate and return only the items than match the condition, but only if the bool UsePredicate is true. I know I can just use LINQ for this, the problem is that everytime I query with LINQ I get a different instance of an IEnumerable, and this needs to be a property, therefore I need to be able to access the same instance of the List from outside the class, because I will be adding and removing items from it, and I cannot do that with the result of a .Where, for example.
I was thinking of a custom IList<T>, but I’m not really sure how to do that.
You have a conceptual problem here. If it is the same instance, how is it supposed to filter by the condition? The reason why LINQ returns a new enumeration on every call is that it runs the query “live”, and multiple queries have to be independent.
That said, you probably shouldn’t have to rely on the property returning the same reference each time. If you rely on the instance being the same, what do you expect to happen when/if someone changes the predicate?
And how is adding or removing items supposed to work/act on a filtered list? If you add an item that would be filtered out, what happens?