Lets say I have two L2S classes generated by the designer with one property as follows:
public class A
{
public bool IsActive {get;set;}
}
public class B
{
public bool IsActive {get;set;}
}
I have a generic DataAccess class as follows:
public class DataAccessBase<T> where T : class
{
NWDataContext dataContext = new NWDataContext();
public IList<T> GetAllActive()
{
return dataContext.GetTable<T>()
.where(T.IsActive == true) -----> How can i do something like this?
.ToList<T>();
}
}
Now from the GetAllActive() how can I return all active objects of either A or B type. My guess is that I have to use reflection to do this but I am very new to reflection. Can anyone point me in the right direction?
You need to assert that
T
implements an interface that definesisActive
What you need to pass to
Enumerable.Where
is aPredicate<T>
. APredicate<T>
is a delegate that can eat instances ofT
and return a bool; you can think of a predicate as representing a property that is eithertrue
orfalse
about instaces ofT
.Now, there is a larger issue which is that unless you put a constraint on
T
, the compiler has no way of knowing thatT
has a publicly readable property namedIsActive
. Thus, you have to define an interface (or a base class) that bothA
andB
implement (or derive from) and tell the methodGetAllActive
thatT
implements (or derives from) this interface (or base class). You can do this by constrainingT
in the definition ofDataAccessBase
. Thus: