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?
What you need to pass to
Enumerable.Whereis aPredicate<T>. APredicate<T>is a delegate that can eat instances ofTand return a bool; you can think of a predicate as representing a property that is eithertrueorfalseabout 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 thatThas a publicly readable property namedIsActive. Thus, you have to define an interface (or a base class) that bothAandBimplement (or derive from) and tell the methodGetAllActivethatTimplements (or derives from) this interface (or base class). You can do this by constrainingTin the definition ofDataAccessBase. Thus: