views:

43

answers:

2

I have a need to create a couple of classes that will serve as base classes for some data functionality I want to implement.

The first, we'll call SessionObjectDataItem looks like this ...

public class ObjectSessionDataItem
{
  public int ID { get; set; }

  public bool IsDirty { get; set; }

  public bool IsNew { get; set; }

  public bool IsRemoved { get; set; }
}

And next I want a List called ObjectSessionDataList and this is where I get stuck.

I can create the class OK ...

public class SessionObjectDataList<SessionObjectDataItem> : List<SessionObjectDataItem>
{

}

where I fall down is trying to define properties on the list that access items in it. For example, I want to write...

public List<SessionObjectDataItem> DirtyItems
{
    get
    {
        return this.Where(d => d.IsDirty).ToList();
    }
}

but VS refuses to recognise the SessionObjectDataItem property IsDirty inside the List object definition.

What I'm trying to end up with is a case where I might define

public class AssociatedDocument : SessionObjectDataItem
{
    ...
}

public class DocumentList : SessionObjectDataList
{

}

And then be able to say...

DocumentList list = new DocumentList();
...
foreach(AssociatedDocument doc in list.DirtyItems)
{
    ...
}

Can I actually do what it is that I'm attempting? Am I just doing it wrong?

+1  A: 

Try to use the generic version Where<T> of the queryable interface:

public List<SessionObjectDataItem> DirtyItems
{
    get
    {
        return this.AsQueryAble().Where<SessionObjectDataItem>(d => d.IsDirty).ToList();
    }
}

Else Where simply assumes d as type Object.

Fge
Fge. Every day is a school day. I've often seen that overload come up in intellisense but have not really understood it's significance. Now I know.
Stuart Hemming
+2  A: 

Generic constraints will help here; you can write a container-class for which the generic type-parameter is constrained to be SessionObjectDataItem or one of its subtypes. This will allow you to construct a generic class that can hold instances of a specific sub-type of SessionObjectDataItem.

public class SessionObjectDataList<T> : List<T> where T : SessionObjectDataItem
{
    public SessionObjectDataList<T> DirtyItems
    {
       get
       {
           return this.Where(d => d.IsDirty).ToList();
       }
    }
}

Usage:

var list = new SessionObjectDataList<AssociatedDocument>();
...

foreach(AssociatedDocument doc in list.DirtyItems)
{
    ...
}
Ani
Bloody marvellous! That solves all of the issues. Thanks Ani.
Stuart Hemming