views:

101

answers:

3

I have abstract class for each Business Object in my app (BO) Also have parent (generic) collection to store all BOs (named BOC - Business Object Collection)

What I would like to archive is created universal method iniside BOC similar to:

public  T GetBusinessObject (lambda_criteria)

So I could call this method similar to:

Employee emp = BOC.GetBusinessObject( Employee.ID=123 )

And method shall return BO meet to specified lambda criteria

Any tips how to archive that?

+1  A: 

Assuming that your BOC inherits from or uses a generic list internally it's not too hard:

T GetBusinesObject<T>( Func<T, bool> predicate )
{
    return this.FirstOrDefault( predicate );
}
Paul Alexander
I'm not sure it would be a generic method - and if it is, surely you'd want an `OfType` / `GetTable` / something? Perhaps lose the `<T>`?
Marc Gravell
+1  A: 

Something like

T GetBusinessObject<T>(Predicate<T> constraint) where T : BO

and then called like

GetBusinessObject<Employee>( e => e.ID = 123 )

perhaps?

Brian
Thanks. But how it will be the body of proposed method?
Maciej
+1  A: 

If this is a generic collection, then the caller should already (via LINQ) be able to use:

BOC<Employee> boc = ...
// checks exactly 1 match, throws if no match
var emp = boc.Single(e => e.ID = 123);
// checks at most 1 match, null if no match
var emp = boc.SingleOrDefault(e => e.ID = 123);
// checks at least one match, throws if no match
var emp = boc.First(e => e.ID = 123);
// returns first match, null if no match
var emp = boc.FirstOrDefault(e => e.ID = 123);

that do?

Marc Gravell