I have to add some "lookup" queries to my C#.NET application. Basically, there will be many tables where they all have the same schema, but contain different values.
I am faced with writing the same code over and over (should be an OO way to do this..)
[edit - below is modified to show more complete info] Anyways, what I would like to do is:
public List<GenericLookupE> GetLookupItems( string what )
{
// create db thing
if ( "regions" == what ) return FetchLookup( db.lkRegions.AsQueryable() );
if ( "partners" == what ) return FetchLookup( db.lkPartners.AsQueryable() );
if ( "funders" == what ) return FetchLookup( db.lkFunders.AsQueryable() );
return null; // or something more intelligent than that =)
}
private List<GenericLookupE> FetchLookup<T>( IQueryable<T> lookup )
{
return lookup.OrderBy( p => p.Sequence ).Select
( p => new GenericLookupE()
{
ID = p.ID
,Label = p.Label
,StateCode = p.StateCode
,Sequence = p.Sequence
}
).ToList();
}
of course, the problem is the compiler doesn't know what 'p => p.Sequence' is. Any ideas?
Thank you all.
Type constraints on generics are your friend. With a base type or interface containing Sequence:
where T : IMyBaseInterface
http://msdn.microsoft.com/en-us/library/bb384067.aspx
Add a common interface to your Т
classes, define Sequence
there, and add a constraint to your generic requiring Т
parameters to implement the common interface.
interface ICommonInterface { // This is an awful name, please pick something better
int Sequence { get }
}
private List<GenericLookupE> FetchLookup<T>( IQueryable<T> lookup ) where T : ICommonInterface {
// Your stuff here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With