Generic method with lambda criteria in the Business Objects collection

I have an abstract class for every business object in my application ( BO ) Also have a parent (shared) collection to store all BOs (called BOC - Collection of Business Objects)

What I would like to archive, a generic iniside BOC method is created, similar to:

public  T GetBusinessObject (lambda_criteria)

      

So I could call this method similar to:

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

      

And the method should return a BO match to the specified lambda criteria

Any tips for archiving them?

+1


a source to share


3 answers


Assuming your BOC inherits or uses a shared list internally, this isn't too hard:



T GetBusinesObject<T>( Func<T, bool> predicate )
{
    return this.FirstOrDefault( predicate );
}

      

+1


a source


Sort of

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

      

and then called like



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

      

possibly?

+1


a source


If it's a common set, then the caller should already (via LINQ) 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);

      

what to do?

+1


a source







All Articles